diff --git a/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/overall_categorization_summary.json b/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/overall_categorization_summary.json deleted file mode 100644 index 2848166ce7e799fab248fd555c7f9c486c43acb1..0000000000000000000000000000000000000000 --- a/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/overall_categorization_summary.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "primevul_train": { - "source_path": "/content/transformed_primevul/2.Normalized_Transformed_PrimeVul/primevul_train_transformed.jsonl", - "stats": { - "total_entries_processed": 175797, - "categories": { - "under_512": { - "count": 0, - "percentage": 0.0, - "max_tokens_setting_for_category": 512 - }, - "512_to_1024": { - "count": 22228, - "percentage": 12.64, - "max_tokens_setting_for_category": 1024 - }, - "1024_to_2048": { - "count": 142464, - "percentage": 81.04, - "max_tokens_setting_for_category": 2048 - }, - "2048_to_4096": { - "count": 8899, - "percentage": 5.06, - "max_tokens_setting_for_category": 4096 - }, - "4096_to_8192": { - "count": 1650, - "percentage": 0.94, - "max_tokens_setting_for_category": 8192 - }, - "8192_to_16384": { - "count": 417, - "percentage": 0.24, - "max_tokens_setting_for_category": 16384 - }, - "16384_to_32768": { - "count": 112, - "percentage": 0.06, - "max_tokens_setting_for_category": 32768 - }, - "over_32768": { - "count": 27, - "percentage": 0.02, - "max_tokens_setting_for_category": null - } - } - }, - "saved_files_details": { - "overall_stats": "categorized_datasets_by_full_entry/primevul_train/primevul_train_categorization_stats.json", - "512_to_1024_pickle": "categorized_datasets_by_full_entry/primevul_train/primevul_train_512_to_1024.pkl", - "512_to_1024_data_file": "categorized_datasets_by_full_entry/primevul_train/primevul_train_512_to_1024.jsonl", - "1024_to_2048_pickle": "categorized_datasets_by_full_entry/primevul_train/primevul_train_1024_to_2048.pkl", - "1024_to_2048_data_file": "categorized_datasets_by_full_entry/primevul_train/primevul_train_1024_to_2048.jsonl", - "2048_to_4096_pickle": "categorized_datasets_by_full_entry/primevul_train/primevul_train_2048_to_4096.pkl", - "2048_to_4096_data_file": "categorized_datasets_by_full_entry/primevul_train/primevul_train_2048_to_4096.jsonl", - "4096_to_8192_pickle": "categorized_datasets_by_full_entry/primevul_train/primevul_train_4096_to_8192.pkl", - "4096_to_8192_data_file": "categorized_datasets_by_full_entry/primevul_train/primevul_train_4096_to_8192.jsonl", - "8192_to_16384_pickle": "categorized_datasets_by_full_entry/primevul_train/primevul_train_8192_to_16384.pkl", - "8192_to_16384_data_file": "categorized_datasets_by_full_entry/primevul_train/primevul_train_8192_to_16384.jsonl", - "16384_to_32768_pickle": "categorized_datasets_by_full_entry/primevul_train/primevul_train_16384_to_32768.pkl", - "16384_to_32768_data_file": "categorized_datasets_by_full_entry/primevul_train/primevul_train_16384_to_32768.jsonl", - "over_32768_pickle": "categorized_datasets_by_full_entry/primevul_train/primevul_train_over_32768.pkl", - "over_32768_data_file": "categorized_datasets_by_full_entry/primevul_train/primevul_train_over_32768.jsonl" - } - }, - "primevul_valid": { - "source_path": "/content/transformed_primevul/2.Normalized_Transformed_PrimeVul/primevul_valid_transformed.jsonl", - "stats": { - "total_entries_processed": 23948, - "categories": { - "under_512": { - "count": 0, - "percentage": 0.0, - "max_tokens_setting_for_category": 512 - }, - "512_to_1024": { - "count": 2894, - "percentage": 12.08, - "max_tokens_setting_for_category": 1024 - }, - "1024_to_2048": { - "count": 19585, - "percentage": 81.78, - "max_tokens_setting_for_category": 2048 - }, - "2048_to_4096": { - "count": 1210, - "percentage": 5.05, - "max_tokens_setting_for_category": 4096 - }, - "4096_to_8192": { - "count": 184, - "percentage": 0.77, - "max_tokens_setting_for_category": 8192 - }, - "8192_to_16384": { - "count": 64, - "percentage": 0.27, - "max_tokens_setting_for_category": 16384 - }, - "16384_to_32768": { - "count": 11, - "percentage": 0.05, - "max_tokens_setting_for_category": 32768 - }, - "over_32768": { - "count": 0, - "percentage": 0.0, - "max_tokens_setting_for_category": null - } - } - }, - "saved_files_details": { - "overall_stats": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_categorization_stats.json", - "512_to_1024_pickle": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_512_to_1024.pkl", - "512_to_1024_data_file": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_512_to_1024.jsonl", - "1024_to_2048_pickle": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_1024_to_2048.pkl", - "1024_to_2048_data_file": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_1024_to_2048.jsonl", - "2048_to_4096_pickle": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_2048_to_4096.pkl", - "2048_to_4096_data_file": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_2048_to_4096.jsonl", - "4096_to_8192_pickle": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_4096_to_8192.pkl", - "4096_to_8192_data_file": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_4096_to_8192.jsonl", - "8192_to_16384_pickle": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_8192_to_16384.pkl", - "8192_to_16384_data_file": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_8192_to_16384.jsonl", - "16384_to_32768_pickle": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_16384_to_32768.pkl", - "16384_to_32768_data_file": "categorized_datasets_by_full_entry/primevul_valid/primevul_valid_16384_to_32768.jsonl" - } - } -} \ No newline at end of file diff --git a/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/primevul_train/primevul_train_1024_to_2048.jsonl b/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/primevul_train/primevul_train_1024_to_2048.jsonl deleted file mode 100644 index beaa018c7f020a0ba0ce28ee9924929dd490616e..0000000000000000000000000000000000000000 --- a/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/primevul_train/primevul_train_1024_to_2048.jsonl +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2630a476a2d5bc7d43bdd9c31efe6230f21b77c26ff6a6463c6998bce5a05c10 -size 131807166 diff --git a/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/primevul_train/primevul_train_1024_to_2048.pkl b/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/primevul_train/primevul_train_1024_to_2048.pkl deleted file mode 100644 index d2dc57b57a17b3f617057e43436fa4768dd980a7..0000000000000000000000000000000000000000 --- a/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/primevul_train/primevul_train_1024_to_2048.pkl +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:10d2672d9019f61f27c9957895f525c4c5ba454ad52729021eeb7c0212eac48b -size 129382617 diff --git a/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/primevul_train/primevul_train_16384_to_32768.jsonl b/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/primevul_train/primevul_train_16384_to_32768.jsonl deleted file mode 100644 index 6cd378c2d50da47f474b613aceb610e0a11477cc..0000000000000000000000000000000000000000 --- a/Primevul_categorized_&_processed_for_finetuning/3.categorized_datasets_by_full_entry/primevul_train/primevul_train_16384_to_32768.jsonl +++ /dev/null @@ -1,112 +0,0 @@ -{"idx":71946,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); \/* write orNT if image->orientation is defined *\/ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); \/* data length=1 *\/ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); \/* PNG uses Exif orientation values *\/ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { \/* Palette, Bilevel, or Opaque Monochrome *\/ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { \/* Undo pixel scaling *\/ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":201849,"input":"void sqlite3Pragma( Parse *pParse, Token *pId1, \/* First part of [schema.]id field *\/ Token *pId2, \/* Second part of [schema.]id field, or NULL *\/ Token *pValue, \/* Token for , or NULL *\/ int minusFlag \/* True if a '-' sign preceded *\/ ){ char *zLeft = 0; \/* Nul-terminated UTF-8 string *\/ char *zRight = 0; \/* Nul-terminated UTF-8 string , or NULL *\/ const char *zDb = 0; \/* The database name *\/ Token *pId; \/* Pointer to token *\/ char *aFcntl[4]; \/* Argument to SQLITE_FCNTL_PRAGMA *\/ int iDb; \/* Database index for *\/ int rc; \/* return value form SQLITE_FCNTL_PRAGMA *\/ sqlite3 *db = pParse->db; \/* The database connection *\/ Db *pDb; \/* The specific database being pragmaed *\/ Vdbe *v = sqlite3GetVdbe(pParse); \/* Prepared statement *\/ const PragmaName *pPragma; \/* The pragma *\/ if( v==0 ) return; sqlite3VdbeRunOnlyOnce(v); pParse->nMem = 2; \/* Interpret the [schema.] part of the pragma statement. iDb is the ** index of the database this pragma is being applied to in db.aDb[]. *\/ iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); if( iDb<0 ) return; pDb = &db->aDb[iDb]; \/* If the temp database has been explicitly named as part of the ** pragma, make sure it is open. *\/ if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ return; } zLeft = sqlite3NameFromToken(db, pId); if( !zLeft ) return; if( minusFlag ){ zRight = sqlite3MPrintf(db, \"-%T\", pValue); }else{ zRight = sqlite3NameFromToken(db, pValue); } assert( pId2 ); zDb = pId2->n>0 ? pDb->zDbSName : 0; if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ goto pragma_out; } \/* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS ** connection. If it returns SQLITE_OK, then assume that the VFS ** handled the pragma and generate a no-op prepared statement. ** ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed, ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file ** object corresponding to the database file to which the pragma ** statement refers. ** ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA ** file control is an array of pointers to strings (char**) in which the ** second element of the array is the name of the pragma and the third ** element is the argument to the pragma or NULL if the pragma has no ** argument. *\/ aFcntl[0] = 0; aFcntl[1] = zLeft; aFcntl[2] = zRight; aFcntl[3] = 0; db->busyHandler.nBusy = 0; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); if( rc==SQLITE_OK ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT); returnSingleText(v, aFcntl[0]); sqlite3_free(aFcntl[0]); goto pragma_out; } if( rc!=SQLITE_NOTFOUND ){ if( aFcntl[0] ){ sqlite3ErrorMsg(pParse, \"%s\", aFcntl[0]); sqlite3_free(aFcntl[0]); } pParse->nErr++; pParse->rc = rc; goto pragma_out; } \/* Locate the pragma in the lookup table *\/ pPragma = pragmaLocate(zLeft); if( pPragma==0 ) goto pragma_out; \/* Make sure the database schema is loaded if the pragma requires that *\/ if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){ if( sqlite3ReadSchema(pParse) ) goto pragma_out; } \/* Register the result column names for pragmas that return results *\/ if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0) ){ setPragmaResultColumnNames(v, pPragma); } \/* Jump to the appropriate pragma handler *\/ switch( pPragma->ePragTyp ){ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) \/* ** PRAGMA [schema.]default_cache_size ** PRAGMA [schema.]default_cache_size=N ** ** The first form reports the current persistent setting for the ** page cache size. The value returned is the maximum number of ** pages in the page cache. The second form sets both the current ** page cache size value and the persistent page cache size value ** stored in the database file. ** ** Older versions of SQLite would set the default cache size to a ** negative number to indicate synchronous=OFF. These days, synchronous ** is always on by default regardless of the sign of the default cache ** size. But continue to take the absolute value of the default cache ** size of historical compatibility. *\/ case PragTyp_DEFAULT_CACHE_SIZE: { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList getCacheSize[] = { { OP_Transaction, 0, 0, 0}, \/* 0 *\/ { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, \/* 1 *\/ { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 2, 0}, { OP_Subtract, 1, 2, 1}, { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 1, 0}, \/* 6 *\/ { OP_Noop, 0, 0, 0}, { OP_ResultRow, 1, 1, 0}, }; VdbeOp *aOp; sqlite3VdbeUsesBtree(v, iDb); if( !zRight ){ pParse->nMem += 2; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize)); aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE; }else{ int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } #endif \/* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED *\/ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) \/* ** PRAGMA [schema.]page_size ** PRAGMA [schema.]page_size=N ** ** The first form reports the current setting for the ** database page size in bytes. The second form sets the ** database page size value. The value can only be set if ** the database has not yet been created. *\/ case PragTyp_PAGE_SIZE: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; returnSingleInt(v, size); }else{ \/* Malloc may fail when setting the page-size, as there is an internal ** buffer that the pager module resizes using sqlite3_realloc(). *\/ db->nextPagesize = sqlite3Atoi(zRight); if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ sqlite3OomFault(db); } } break; } \/* ** PRAGMA [schema.]secure_delete ** PRAGMA [schema.]secure_delete=ON\/OFF\/FAST ** ** The first form reports the current setting for the ** secure_delete flag. The second form changes the secure_delete ** flag setting and reports the new value. *\/ case PragTyp_SECURE_DELETE: { Btree *pBt = pDb->pBt; int b = -1; assert( pBt!=0 ); if( zRight ){ if( sqlite3_stricmp(zRight, \"fast\")==0 ){ b = 2; }else{ b = sqlite3GetBoolean(zRight, 0); } } if( pId2->n==0 && b>=0 ){ int ii; for(ii=0; iinDb; ii++){ sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); } } b = sqlite3BtreeSecureDelete(pBt, b); returnSingleInt(v, b); break; } \/* ** PRAGMA [schema.]max_page_count ** PRAGMA [schema.]max_page_count=N ** ** The first form reports the current setting for the ** maximum number of pages in the database file. The ** second form attempts to change this setting. Both ** forms return the current setting. ** ** The absolute value of N is used. This is undocumented and might ** change. The only purpose is to provide an easy way to test ** the sqlite3AbsInt32() function. ** ** PRAGMA [schema.]page_count ** ** Return the number of pages in the specified database. *\/ case PragTyp_PAGE_COUNT: { int iReg; sqlite3CodeVerifySchema(pParse, iDb); iReg = ++pParse->nMem; if( sqlite3Tolower(zLeft[0])=='p' ){ sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); }else{ sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3AbsInt32(sqlite3Atoi(zRight))); } sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); break; } \/* ** PRAGMA [schema.]locking_mode ** PRAGMA [schema.]locking_mode = (normal|exclusive) *\/ case PragTyp_LOCKING_MODE: { const char *zRet = \"normal\"; int eMode = getLockingMode(zRight); if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){ \/* Simple \"PRAGMA locking_mode;\" statement. This is a query for ** the current default locking mode (which may be different to ** the locking-mode of the main database). *\/ eMode = db->dfltLockMode; }else{ Pager *pPager; if( pId2->n==0 ){ \/* This indicates that no database name was specified as part ** of the PRAGMA command. In this case the locking-mode must be ** set on all attached databases, as well as the main db file. ** ** Also, the sqlite3.dfltLockMode variable is set so that ** any subsequently attached databases also use the specified ** locking mode. *\/ int ii; assert(pDb==&db->aDb[0]); for(ii=2; iinDb; ii++){ pPager = sqlite3BtreePager(db->aDb[ii].pBt); sqlite3PagerLockingMode(pPager, eMode); } db->dfltLockMode = (u8)eMode; } pPager = sqlite3BtreePager(pDb->pBt); eMode = sqlite3PagerLockingMode(pPager, eMode); } assert( eMode==PAGER_LOCKINGMODE_NORMAL || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ zRet = \"exclusive\"; } returnSingleText(v, zRet); break; } \/* ** PRAGMA [schema.]journal_mode ** PRAGMA [schema.]journal_mode = ** (delete|persist|off|truncate|memory|wal|off) *\/ case PragTyp_JOURNAL_MODE: { int eMode; \/* One of the PAGER_JOURNALMODE_XXX symbols *\/ int ii; \/* Loop counter *\/ if( zRight==0 ){ \/* If there is no \"=MODE\" part of the pragma, do a query for the ** current mode *\/ eMode = PAGER_JOURNALMODE_QUERY; }else{ const char *zMode; int n = sqlite3Strlen30(zRight); for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; } if( !zMode ){ \/* If the \"=MODE\" part does not match any known journal mode, ** then do a query *\/ eMode = PAGER_JOURNALMODE_QUERY; } if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){ \/* Do not allow journal-mode \"OFF\" in defensive since the database ** can become corrupted using ordinary SQL when the journal is off *\/ eMode = PAGER_JOURNALMODE_QUERY; } } if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ \/* Convert \"PRAGMA journal_mode\" into \"PRAGMA main.journal_mode\" *\/ iDb = 0; pId2->n = 1; } for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3VdbeUsesBtree(v, ii); sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); } } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); break; } \/* ** PRAGMA [schema.]journal_size_limit ** PRAGMA [schema.]journal_size_limit=N ** ** Get or set the size limit on rollback journal files. *\/ case PragTyp_JOURNAL_SIZE_LIMIT: { Pager *pPager = sqlite3BtreePager(pDb->pBt); i64 iLimit = -2; if( zRight ){ sqlite3DecOrHexToI64(zRight, &iLimit); if( iLimit<-1 ) iLimit = -1; } iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); returnSingleInt(v, iLimit); break; } #endif \/* SQLITE_OMIT_PAGER_PRAGMAS *\/ \/* ** PRAGMA [schema.]auto_vacuum ** PRAGMA [schema.]auto_vacuum=N ** ** Get or set the value of the database 'auto-vacuum' parameter. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL *\/ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_AUTO_VACUUM: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt)); }else{ int eAuto = getAutoVacuum(zRight); assert( eAuto>=0 && eAuto<=2 ); db->nextAutovac = (u8)eAuto; \/* Call SetAutoVacuum() to set initialize the internal auto and ** incr-vacuum flags. This is required in case this connection ** creates the database file. It is important that it is created ** as an auto-vacuum capable db. *\/ rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ \/* When setting the auto_vacuum mode to either \"full\" or ** \"incremental\", write the value of meta[6] in the database ** file. Before writing to meta[6], check that meta[3] indicates ** that this really is an auto-vacuum capable database. *\/ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList setMeta6[] = { { OP_Transaction, 0, 1, 0}, \/* 0 *\/ { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE}, { OP_If, 1, 0, 0}, \/* 2 *\/ { OP_Halt, SQLITE_OK, OE_Abort, 0}, \/* 3 *\/ { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, \/* 4 *\/ }; VdbeOp *aOp; int iAddr = sqlite3VdbeCurrentAddr(v); sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[2].p2 = iAddr+4; aOp[4].p1 = iDb; aOp[4].p3 = eAuto - 1; sqlite3VdbeUsesBtree(v, iDb); } } break; } #endif \/* ** PRAGMA [schema.]incremental_vacuum(N) ** ** Do N steps of incremental vacuuming on a database. *\/ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_INCREMENTAL_VACUUM: { int iLimit, addr; if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ iLimit = 0x7fffffff; } sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v); sqlite3VdbeAddOp1(v, OP_ResultRow, 1); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr); break; } #endif #ifndef SQLITE_OMIT_PAGER_PRAGMAS \/* ** PRAGMA [schema.]cache_size ** PRAGMA [schema.]cache_size=N ** ** The first form reports the current local setting for the ** page cache size. The second form sets the local ** page cache size value. If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. *\/ case PragTyp_CACHE_SIZE: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, pDb->pSchema->cache_size); }else{ int size = sqlite3Atoi(zRight); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } \/* ** PRAGMA [schema.]cache_spill ** PRAGMA cache_spill=BOOLEAN ** PRAGMA [schema.]cache_spill=N ** ** The first form reports the current local setting for the ** page cache spill size. The second form turns cache spill on ** or off. When turnning cache spill on, the size is set to the ** current cache_size. The third form sets a spill size that ** may be different form the cache size. ** If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. ** ** If the number of cache_spill pages is less then the number of ** cache_size pages, no spilling occurs until the page count exceeds ** the number of cache_size pages. ** ** The cache_spill=BOOLEAN setting applies to all attached schemas, ** not just the schema specified. *\/ case PragTyp_CACHE_SPILL: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, (db->flags & SQLITE_CacheSpill)==0 ? 0 : sqlite3BtreeSetSpillSize(pDb->pBt,0)); }else{ int size = 1; if( sqlite3GetInt32(zRight, &size) ){ sqlite3BtreeSetSpillSize(pDb->pBt, size); } if( sqlite3GetBoolean(zRight, size!=0) ){ db->flags |= SQLITE_CacheSpill; }else{ db->flags &= ~(u64)SQLITE_CacheSpill; } setAllPagerFlags(db); } break; } \/* ** PRAGMA [schema.]mmap_size(N) ** ** Used to set mapping size limit. The mapping size limit is ** used to limit the aggregate size of all memory mapped regions of the ** database file. If this parameter is set to zero, then memory mapping ** is not used at all. If N is negative, then the default memory map ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. ** The parameter N is measured in bytes. ** ** This value is advisory. The underlying VFS is free to memory map ** as little or as much as it wants. Except, if N is set to 0 then the ** upper layers will never invoke the xFetch interfaces to the VFS. *\/ case PragTyp_MMAP_SIZE: { sqlite3_int64 sz; #if SQLITE_MAX_MMAP_SIZE>0 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( zRight ){ int ii; sqlite3DecOrHexToI64(zRight, &sz); if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; if( pId2->n==0 ) db->szMmap = sz; for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); } } } sz = -1; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); #else sz = 0; rc = SQLITE_OK; #endif if( rc==SQLITE_OK ){ returnSingleInt(v, sz); }else if( rc!=SQLITE_NOTFOUND ){ pParse->nErr++; pParse->rc = rc; } break; } \/* ** PRAGMA temp_store ** PRAGMA temp_store = \"default\"|\"memory\"|\"file\" ** ** Return or set the local value of the temp_store flag. Changing ** the local value does not make changes to the disk file and the default ** value will be restored the next time the database is opened. ** ** Note that it is possible for the library compile-time options to ** override this setting *\/ case PragTyp_TEMP_STORE: { if( !zRight ){ returnSingleInt(v, db->temp_store); }else{ changeTempStorage(pParse, zRight); } break; } \/* ** PRAGMA temp_store_directory ** PRAGMA temp_store_directory = \"\"|\"directory_name\" ** ** Return or set the local value of the temp_store_directory flag. Changing ** the value sets a specific directory to be used for temporary files. ** Setting to a null string reverts to the default temporary directory search. ** If temporary directory is changed, then invalidateTempStorage. ** *\/ case PragTyp_TEMP_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, sqlite3_temp_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, \"not a writable directory\"); goto pragma_out; } } if( SQLITE_TEMP_STORE==0 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) || (SQLITE_TEMP_STORE==2 && db->temp_store==1) ){ invalidateTempStorage(pParse); } sqlite3_free(sqlite3_temp_directory); if( zRight[0] ){ sqlite3_temp_directory = sqlite3_mprintf(\"%s\", zRight); }else{ sqlite3_temp_directory = 0; } #endif \/* SQLITE_OMIT_WSD *\/ } break; } #if SQLITE_OS_WIN \/* ** PRAGMA data_store_directory ** PRAGMA data_store_directory = \"\"|\"directory_name\" ** ** Return or set the local value of the data_store_directory flag. Changing ** the value sets a specific directory to be used for database files that ** were specified with a relative pathname. Setting to a null string reverts ** to the default database directory, which for database files specified with ** a relative path will probably be based on the current directory for the ** process. Database file specified with an absolute path are not impacted ** by this setting, regardless of its value. ** *\/ case PragTyp_DATA_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, sqlite3_data_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, \"not a writable directory\"); goto pragma_out; } } sqlite3_free(sqlite3_data_directory); if( zRight[0] ){ sqlite3_data_directory = sqlite3_mprintf(\"%s\", zRight); }else{ sqlite3_data_directory = 0; } #endif \/* SQLITE_OMIT_WSD *\/ } break; } #endif #if SQLITE_ENABLE_LOCKING_STYLE \/* ** PRAGMA [schema.]lock_proxy_file ** PRAGMA [schema.]lock_proxy_file = \":auto:\"|\"lock_file_path\" ** ** Return or set the value of the lock_proxy_file flag. Changing ** the value sets a specific file to be used for database access locks. ** *\/ case PragTyp_LOCK_PROXY_FILE: { if( !zRight ){ Pager *pPager = sqlite3BtreePager(pDb->pBt); char *proxy_file_path = NULL; sqlite3_file *pFile = sqlite3PagerFile(pPager); sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, &proxy_file_path); returnSingleText(v, proxy_file_path); }else{ Pager *pPager = sqlite3BtreePager(pDb->pBt); sqlite3_file *pFile = sqlite3PagerFile(pPager); int res; if( zRight[0] ){ res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, zRight); } else { res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, NULL); } if( res!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, \"failed to set lock proxy file\"); goto pragma_out; } } break; } #endif \/* SQLITE_ENABLE_LOCKING_STYLE *\/ \/* ** PRAGMA [schema.]synchronous ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA ** ** Return or set the local value of the synchronous flag. Changing ** the local value does not make changes to the disk file and the ** default value will be restored the next time the database is ** opened. *\/ case PragTyp_SYNCHRONOUS: { if( !zRight ){ returnSingleInt(v, pDb->safety_level-1); }else{ if( !db->autoCommit ){ sqlite3ErrorMsg(pParse, \"Safety level may not be changed inside a transaction\"); }else if( iDb!=1 ){ int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK; if( iLevel==0 ) iLevel = 1; pDb->safety_level = iLevel; pDb->bSyncSet = 1; setAllPagerFlags(db); } } break; } #endif \/* SQLITE_OMIT_PAGER_PRAGMAS *\/ #ifndef SQLITE_OMIT_FLAG_PRAGMAS case PragTyp_FLAG: { if( zRight==0 ){ setPragmaResultColumnNames(v, pPragma); returnSingleInt(v, (db->flags & pPragma->iArg)!=0 ); }else{ u64 mask = pPragma->iArg; \/* Mask of bits to set or clear. *\/ if( db->autoCommit==0 ){ \/* Foreign key support may not be enabled or disabled while not ** in auto-commit mode. *\/ mask &= ~(SQLITE_ForeignKeys); } #if SQLITE_USER_AUTHENTICATION if( db->auth.authLevel==UAUTH_User ){ \/* Do not allow non-admin users to modify the schema arbitrarily *\/ mask &= ~(SQLITE_WriteSchema); } #endif if( sqlite3GetBoolean(zRight, 0) ){ db->flags |= mask; }else{ db->flags &= ~mask; if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; } \/* Many of the flag-pragmas modify the code generated by the SQL ** compiler (eg. count_changes). So add an opcode to expire all ** compiled SQL statements after modifying a pragma value. *\/ sqlite3VdbeAddOp0(v, OP_Expire); setAllPagerFlags(db); } break; } #endif \/* SQLITE_OMIT_FLAG_PRAGMAS *\/ #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS \/* ** PRAGMA table_info() ** ** Return a single row for each column of the named table. The columns of ** the returned data set are: ** ** cid: Column id (numbered from left to right, starting at 0) ** name: Column name ** type: Column declaration type. ** notnull: True if 'NOT NULL' is part of column declaration ** dflt_value: The default value for the column, if any. ** pk: Non-zero for PK fields. *\/ case PragTyp_TABLE_INFO: if( zRight ){ Table *pTab; pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); if( pTab ){ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); int i, k; int nHidden = 0; Column *pCol; Index *pPk = sqlite3PrimaryKeyIndex(pTab); pParse->nMem = 7; sqlite3CodeVerifySchema(pParse, iTabDb); sqlite3ViewGetColumnNames(pParse, pTab); for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ int isHidden = 0; if( pCol->colFlags & COLFLAG_NOINSERT ){ if( pPragma->iArg==0 ){ nHidden++; continue; } if( pCol->colFlags & COLFLAG_VIRTUAL ){ isHidden = 2; \/* GENERATED ALWAYS AS ... VIRTUAL *\/ }else if( pCol->colFlags & COLFLAG_STORED ){ isHidden = 3; \/* GENERATED ALWAYS AS ... STORED *\/ }else{ assert( pCol->colFlags & COLFLAG_HIDDEN ); isHidden = 1; \/* HIDDEN *\/ } } if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ k = 0; }else if( pPk==0 ){ k = 1; }else{ for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){} } assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 ); sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? \"issisii\" : \"issisi\", i-nHidden, pCol->zName, sqlite3ColumnType(pCol,\"\"), pCol->notNull ? 1 : 0, pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0, k, isHidden); } } } break; #ifdef SQLITE_DEBUG case PragTyp_STATS: { Index *pIdx; HashElem *i; pParse->nMem = 5; sqlite3CodeVerifySchema(pParse, iDb); for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ Table *pTab = sqliteHashData(i); sqlite3VdbeMultiLoad(v, 1, \"ssiii\", pTab->zName, 0, pTab->szTabRow, pTab->nRowLogEst, pTab->tabFlags); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ sqlite3VdbeMultiLoad(v, 2, \"siiiX\", pIdx->zName, pIdx->szIdxRow, pIdx->aiRowLogEst[0], pIdx->hasStat1); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); } } } break; #endif case PragTyp_INDEX_INFO: if( zRight ){ Index *pIdx; Table *pTab; pIdx = sqlite3FindIndex(db, zRight, zDb); if( pIdx==0 ){ \/* If there is no index named zRight, check to see if there is a ** WITHOUT ROWID table named zRight, and if there is, show the ** structure of the PRIMARY KEY index for that table. *\/ pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); if( pTab && !HasRowid(pTab) ){ pIdx = sqlite3PrimaryKeyIndex(pTab); } } if( pIdx ){ int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema); int i; int mx; if( pPragma->iArg ){ \/* PRAGMA index_xinfo (newer version with more rows and columns) *\/ mx = pIdx->nColumn; pParse->nMem = 6; }else{ \/* PRAGMA index_info (legacy version) *\/ mx = pIdx->nKeyCol; pParse->nMem = 3; } pTab = pIdx->pTable; sqlite3CodeVerifySchema(pParse, iIdxDb); assert( pParse->nMem<=pPragma->nPragCName ); for(i=0; iaiColumn[i]; sqlite3VdbeMultiLoad(v, 1, \"iisX\", i, cnum, cnum<0 ? 0 : pTab->aCol[cnum].zName); if( pPragma->iArg ){ sqlite3VdbeMultiLoad(v, 4, \"isiX\", pIdx->aSortOrder[i], pIdx->azColl[i], inKeyCol); } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem); } } } break; case PragTyp_INDEX_LIST: if( zRight ){ Index *pIdx; Table *pTab; int i; pTab = sqlite3FindTable(db, zRight, zDb); if( pTab ){ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); pParse->nMem = 5; sqlite3CodeVerifySchema(pParse, iTabDb); for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ const char *azOrigin[] = { \"c\", \"u\", \"pk\" }; sqlite3VdbeMultiLoad(v, 1, \"isisi\", i, pIdx->zName, IsUniqueIndex(pIdx), azOrigin[pIdx->idxType], pIdx->pPartIdxWhere!=0); } } } break; case PragTyp_DATABASE_LIST: { int i; pParse->nMem = 3; for(i=0; inDb; i++){ if( db->aDb[i].pBt==0 ) continue; assert( db->aDb[i].zDbSName!=0 ); sqlite3VdbeMultiLoad(v, 1, \"iss\", i, db->aDb[i].zDbSName, sqlite3BtreeGetFilename(db->aDb[i].pBt)); } } break; case PragTyp_COLLATION_LIST: { int i = 0; HashElem *p; pParse->nMem = 2; for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ CollSeq *pColl = (CollSeq *)sqliteHashData(p); sqlite3VdbeMultiLoad(v, 1, \"is\", i++, pColl->zName); } } break; #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS case PragTyp_FUNCTION_LIST: { int i; HashElem *j; FuncDef *p; pParse->nMem = 2; for(i=0; iu.pHash ){ if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue; sqlite3VdbeMultiLoad(v, 1, \"si\", p->zName, 1); } } for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){ p = (FuncDef*)sqliteHashData(j); sqlite3VdbeMultiLoad(v, 1, \"si\", p->zName, 0); } } break; #ifndef SQLITE_OMIT_VIRTUALTABLE case PragTyp_MODULE_LIST: { HashElem *j; pParse->nMem = 1; for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){ Module *pMod = (Module*)sqliteHashData(j); sqlite3VdbeMultiLoad(v, 1, \"s\", pMod->zName); } } break; #endif \/* SQLITE_OMIT_VIRTUALTABLE *\/ case PragTyp_PRAGMA_LIST: { int i; for(i=0; ipFKey; if( pFK ){ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); int i = 0; pParse->nMem = 8; sqlite3CodeVerifySchema(pParse, iTabDb); while(pFK){ int j; for(j=0; jnCol; j++){ sqlite3VdbeMultiLoad(v, 1, \"iissssss\", i, j, pFK->zTo, pTab->aCol[pFK->aCol[j].iFrom].zName, pFK->aCol[j].zCol, actionName(pFK->aAction[1]), \/* ON UPDATE *\/ actionName(pFK->aAction[0]), \/* ON DELETE *\/ \"NONE\"); } ++i; pFK = pFK->pNextFrom; } } } } break; #endif \/* !defined(SQLITE_OMIT_FOREIGN_KEY) *\/ #ifndef SQLITE_OMIT_FOREIGN_KEY #ifndef SQLITE_OMIT_TRIGGER case PragTyp_FOREIGN_KEY_CHECK: { FKey *pFK; \/* A foreign key constraint *\/ Table *pTab; \/* Child table contain \"REFERENCES\" keyword *\/ Table *pParent; \/* Parent table that child points to *\/ Index *pIdx; \/* Index in the parent table *\/ int i; \/* Loop counter: Foreign key number for pTab *\/ int j; \/* Loop counter: Field of the foreign key *\/ HashElem *k; \/* Loop counter: Next table in schema *\/ int x; \/* result variable *\/ int regResult; \/* 3 registers to hold a result row *\/ int regKey; \/* Register to hold key for checking the FK *\/ int regRow; \/* Registers to hold a row from pTab *\/ int addrTop; \/* Top of a loop checking foreign keys *\/ int addrOk; \/* Jump here if the key is OK *\/ int *aiCols; \/* child to parent column mapping *\/ regResult = pParse->nMem+1; pParse->nMem += 4; regKey = ++pParse->nMem; regRow = ++pParse->nMem; k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); while( k ){ int iTabDb; if( zRight ){ pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); k = 0; }else{ pTab = (Table*)sqliteHashData(k); k = sqliteHashNext(k); } if( pTab==0 || pTab->pFKey==0 ) continue; iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3CodeVerifySchema(pParse, iTabDb); sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName); if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead); sqlite3VdbeLoadString(v, regResult, pTab->zName); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); if( pParent==0 ) continue; pIdx = 0; sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName); x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); if( x==0 ){ if( pIdx==0 ){ sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead); }else{ sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); } }else{ k = 0; break; } } assert( pParse->nErr>0 || pFK==0 ); if( pFK ) break; if( pParse->nTabnTab = i; addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); pIdx = 0; aiCols = 0; if( pParent ){ x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); assert( x==0 ); } addrOk = sqlite3VdbeMakeLabel(pParse); \/* Generate code to read the child key values into registers ** regRow..regRow+n. If any of the child key values are NULL, this ** row cannot cause an FK violation. Jump directly to addrOk in ** this case. *\/ for(j=0; jnCol; j++){ int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom; sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j); sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v); } \/* Generate code to query the parent index for a matching parent ** key. If a match is found, jump to addrOk. *\/ if( pIdx ){ sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey, sqlite3IndexAffinityStr(db,pIdx), pFK->nCol); sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); VdbeCoverage(v); }else if( pParent ){ int jmp = sqlite3VdbeCurrentAddr(v)+2; sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v); sqlite3VdbeGoto(v, addrOk); assert( pFK->nCol==1 ); } \/* Generate code to report an FK violation to the caller. *\/ if( HasRowid(pTab) ){ sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1); } sqlite3VdbeMultiLoad(v, regResult+2, \"siX\", pFK->zTo, i-1); sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); sqlite3VdbeResolveLabel(v, addrOk); sqlite3DbFree(db, aiCols); } sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrTop); } } break; #endif \/* !defined(SQLITE_OMIT_TRIGGER) *\/ #endif \/* !defined(SQLITE_OMIT_FOREIGN_KEY) *\/ #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA \/* Reinstall the LIKE and GLOB functions. The variant of LIKE ** used will be case sensitive or not depending on the RHS. *\/ case PragTyp_CASE_SENSITIVE_LIKE: { if( zRight ){ sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); } } break; #endif \/* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA *\/ #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 #endif #ifndef SQLITE_OMIT_INTEGRITY_CHECK \/* PRAGMA integrity_check ** PRAGMA integrity_check(N) ** PRAGMA quick_check ** PRAGMA quick_check(N) ** ** Verify the integrity of the database. ** ** The \"quick_check\" is reduced version of ** integrity_check designed to detect most database corruption ** without the overhead of cross-checking indexes. Quick_check ** is linear time wherease integrity_check is O(NlogN). *\/ case PragTyp_INTEGRITY_CHECK: { int i, j, addr, mxErr; int isQuick = (sqlite3Tolower(zLeft[0])=='q'); \/* If the PRAGMA command was of the form \"PRAGMA .integrity_check\", ** then iDb is set to the index of the database identified by . ** In this case, the integrity of database iDb only is verified by ** the VDBE created below. ** ** Otherwise, if the command was simply \"PRAGMA integrity_check\" (or ** \"PRAGMA quick_check\"), then iDb is set to 0. In this case, set iDb ** to -1 here, to indicate that the VDBE should verify the integrity ** of all attached databases. *\/ assert( iDb>=0 ); assert( iDb==0 || pId2->z ); if( pId2->z==0 ) iDb = -1; \/* Initialize the VDBE program *\/ pParse->nMem = 6; \/* Set the maximum error count *\/ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; if( zRight ){ sqlite3GetInt32(zRight, &mxErr); if( mxErr<=0 ){ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; } } sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); \/* reg[1] holds errors left *\/ \/* Do an integrity check on each database file *\/ for(i=0; inDb; i++){ HashElem *x; \/* For looping over tables in the schema *\/ Hash *pTbls; \/* Set of all tables in the schema *\/ int *aRoot; \/* Array of root page numbers of all btrees *\/ int cnt = 0; \/* Number of entries in aRoot[] *\/ int mxIdx = 0; \/* Maximum number of indexes for any table *\/ if( OMIT_TEMPDB && i==1 ) continue; if( iDb>=0 && i!=iDb ) continue; sqlite3CodeVerifySchema(pParse, i); \/* Do an integrity check of the B-Tree ** ** Begin by finding the root pages numbers ** for all tables and indices in the database. *\/ assert( sqlite3SchemaMutexHeld(db, i, 0) ); pTbls = &db->aDb[i].pSchema->tblHash; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); \/* Current table *\/ Index *pIdx; \/* An index on pTab *\/ int nIdx; \/* Number of indexes on pTab *\/ if( HasRowid(pTab) ) cnt++; for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } if( nIdx>mxIdx ) mxIdx = nIdx; } aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); if( aRoot==0 ) break; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ aRoot[++cnt] = pIdx->tnum; } } aRoot[0] = cnt; \/* Make sure sufficient number of registers have been allocated *\/ pParse->nMem = MAX( pParse->nMem, 8+mxIdx ); sqlite3ClearTempRegCache(pParse); \/* Do the b-tree integrity checks *\/ sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY); sqlite3VdbeChangeP5(v, (u8)i); addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, sqlite3MPrintf(db, \"*** in database %s ***\\n\", db->aDb[i].zDbSName), P4_DYNAMIC); sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3); integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, addr); \/* Make sure all the indices are constructed correctly. *\/ for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx, *pPk; Index *pPrior = 0; int loopTop; int iDataCur, iIdxCur; int r1 = -1; if( pTab->tnum<1 ) continue; \/* Skip VIEWs or VIRTUAL TABLEs *\/ pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0, 1, 0, &iDataCur, &iIdxCur); \/* reg[7] counts the number of entries in the table. ** reg[8+i] counts the number of entries in the i-th index *\/ sqlite3VdbeAddOp2(v, OP_Integer, 0, 7); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); \/* index entries counter *\/ } assert( pParse->nMem>=8+j ); assert( sqlite3NoTempsInRange(pParse,1,7+j) ); sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v); loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); if( !isQuick ){ \/* Sanity check on record header decoding *\/ sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); } \/* Verify that all NOT NULL columns really are NOT NULL *\/ for(j=0; jnCol; j++){ char *zErr; int jmp2; if( j==pTab->iPKey ) continue; if( pTab->aCol[j].notNull==0 ) continue; sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v); zErr = sqlite3MPrintf(db, \"NULL value in %s.%s\", pTab->zName, pTab->aCol[j].zName); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, jmp2); } \/* Verify CHECK constraints *\/ if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0); if( db->mallocFailed==0 ){ int addrCkFault = sqlite3VdbeMakeLabel(pParse); int addrCkOk = sqlite3VdbeMakeLabel(pParse); char *zErr; int k; pParse->iSelfTab = iDataCur + 1; for(k=pCheck->nExpr-1; k>0; k--){ sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0); } sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, SQLITE_JUMPIFNULL); sqlite3VdbeResolveLabel(v, addrCkFault); pParse->iSelfTab = 0; zErr = sqlite3MPrintf(db, \"CHECK constraint failed in %s\", pTab->zName); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); integrityCheckResultRow(v); sqlite3VdbeResolveLabel(v, addrCkOk); } sqlite3ExprListDelete(db, pCheck); } if( !isQuick ){ \/* Omit the remaining tests for quick_check *\/ \/* Validate index entries for the current row *\/ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int jmp2, jmp3, jmp4, jmp5; int ckUniq = sqlite3VdbeMakeLabel(pParse); if( pPk==pIdx ) continue; r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3, pPrior, r1); pPrior = pIdx; sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);\/* increment entry count *\/ \/* Verify that an index entry exists for the current table row *\/ jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, pIdx->nColumn); VdbeCoverage(v); sqlite3VdbeLoadString(v, 3, \"row \"); sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); sqlite3VdbeLoadString(v, 4, \" missing from index \"); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); jmp4 = integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, jmp2); \/* For UNIQUE indexes, verify that only one entry exists with the ** current key. The entry is unique if (1) any column is NULL ** or (2) the next entry has a different key *\/ if( IsUniqueIndex(pIdx) ){ int uniqOk = sqlite3VdbeMakeLabel(pParse); int jmp6; int kk; for(kk=0; kknKeyCol; kk++){ int iCol = pIdx->aiColumn[kk]; assert( iCol!=XN_ROWID && iColnCol ); if( iCol>=0 && pTab->aCol[iCol].notNull ) continue; sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk); VdbeCoverage(v); } jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v); sqlite3VdbeGoto(v, uniqOk); sqlite3VdbeJumpHere(v, jmp6); sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1, pIdx->nKeyCol); VdbeCoverage(v); sqlite3VdbeLoadString(v, 3, \"non-unique entry in index \"); sqlite3VdbeGoto(v, jmp5); sqlite3VdbeResolveLabel(v, uniqOk); } sqlite3VdbeJumpHere(v, jmp4); sqlite3ResolvePartIdxLabel(pParse, jmp3); } } sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v); sqlite3VdbeJumpHere(v, loopTop-1); #ifndef SQLITE_OMIT_BTREECOUNT if( !isQuick ){ sqlite3VdbeLoadString(v, 2, \"wrong # of entries in index \"); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ if( pPk==pIdx ) continue; sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); sqlite3VdbeLoadString(v, 4, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3); integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, addr); } } #endif \/* SQLITE_OMIT_BTREECOUNT *\/ } } { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList endCode[] = { { OP_AddImm, 1, 0, 0}, \/* 0 *\/ { OP_IfNotZero, 1, 4, 0}, \/* 1 *\/ { OP_String8, 0, 3, 0}, \/* 2 *\/ { OP_ResultRow, 3, 1, 0}, \/* 3 *\/ { OP_Halt, 0, 0, 0}, \/* 4 *\/ { OP_String8, 0, 3, 0}, \/* 5 *\/ { OP_Goto, 0, 3, 0}, \/* 6 *\/ }; VdbeOp *aOp; aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn); if( aOp ){ aOp[0].p2 = 1-mxErr; aOp[2].p4type = P4_STATIC; aOp[2].p4.z = \"ok\"; aOp[5].p4type = P4_STATIC; aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT); } sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2); } } break; #endif \/* SQLITE_OMIT_INTEGRITY_CHECK *\/ #ifndef SQLITE_OMIT_UTF16 \/* ** PRAGMA encoding ** PRAGMA encoding = \"utf-8\"|\"utf-16\"|\"utf-16le\"|\"utf-16be\" ** ** In its first form, this pragma returns the encoding of the main ** database. If the database is not initialized, it is initialized now. ** ** The second form of this pragma is a no-op if the main database file ** has not already been initialized. In this case it sets the default ** encoding that will be used for the main database file if a new file ** is created. If an existing main database file is opened, then the ** default text encoding for the existing database is used. ** ** In all cases new databases created using the ATTACH command are ** created to use the same default text encoding as the main database. If ** the main database has not been initialized and\/or created when ATTACH ** is executed, this is done before the ATTACH operation. ** ** In the second form this pragma sets the text encoding to be used in ** new database files created using this database handle. It is only ** useful if invoked immediately after the main database i *\/ case PragTyp_ENCODING: { static const struct EncName { char *zName; u8 enc; } encnames[] = { { \"UTF8\", SQLITE_UTF8 }, { \"UTF-8\", SQLITE_UTF8 }, \/* Must be element [1] *\/ { \"UTF-16le\", SQLITE_UTF16LE }, \/* Must be element [2] *\/ { \"UTF-16be\", SQLITE_UTF16BE }, \/* Must be element [3] *\/ { \"UTF16le\", SQLITE_UTF16LE }, { \"UTF16be\", SQLITE_UTF16BE }, { \"UTF-16\", 0 }, \/* SQLITE_UTF16NATIVE *\/ { \"UTF16\", 0 }, \/* SQLITE_UTF16NATIVE *\/ { 0, 0 } }; const struct EncName *pEnc; if( !zRight ){ \/* \"PRAGMA encoding\" *\/ if( sqlite3ReadSchema(pParse) ) goto pragma_out; assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); returnSingleText(v, encnames[ENC(pParse->db)].zName); }else{ \/* \"PRAGMA encoding = XXX\" *\/ \/* Only change the value of sqlite.enc if the database handle is not ** initialized. If the main database exists, the new sqlite.enc value ** will be overwritten when the schema is next loaded. If it does not ** already exists, it will be created to use the new encoding value. *\/ if( !(DbHasProperty(db, 0, DB_SchemaLoaded)) || DbHasProperty(db, 0, DB_Empty) ){ for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ SCHEMA_ENC(db) = ENC(db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; break; } } if( !pEnc->zName ){ sqlite3ErrorMsg(pParse, \"unsupported encoding: %s\", zRight); } } } } break; #endif \/* SQLITE_OMIT_UTF16 *\/ #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS \/* ** PRAGMA [schema.]schema_version ** PRAGMA [schema.]schema_version = ** ** PRAGMA [schema.]user_version ** PRAGMA [schema.]user_version = ** ** PRAGMA [schema.]freelist_count ** ** PRAGMA [schema.]data_version ** ** PRAGMA [schema.]application_id ** PRAGMA [schema.]application_id = ** ** The pragma's schema_version and user_version are used to set or get ** the value of the schema-version and user-version, respectively. Both ** the schema-version and the user-version are 32-bit signed integers ** stored in the database header. ** ** The schema-cookie is usually only manipulated internally by SQLite. It ** is incremented by SQLite whenever the database schema is modified (by ** creating or dropping a table or index). The schema version is used by ** SQLite each time a query is executed to ensure that the internal cache ** of the schema used when compiling the SQL query matches the schema of ** the database against which the compiled query is actually executed. ** Subverting this mechanism by using \"PRAGMA schema_version\" to modify ** the schema-version is potentially dangerous and may lead to program ** crashes or database corruption. Use with caution! ** ** The user-version is not used internally by SQLite. It may be used by ** applications for any purpose. *\/ case PragTyp_HEADER_VALUE: { int iCookie = pPragma->iArg; \/* Which cookie to read or write *\/ sqlite3VdbeUsesBtree(v, iDb); if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){ \/* Write the specified cookie value *\/ static const VdbeOpList setCookie[] = { { OP_Transaction, 0, 1, 0}, \/* 0 *\/ { OP_SetCookie, 0, 0, 0}, \/* 1 *\/ }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p2 = iCookie; aOp[1].p3 = sqlite3Atoi(zRight); }else{ \/* Read the specified cookie value *\/ static const VdbeOpList readCookie[] = { { OP_Transaction, 0, 0, 0}, \/* 0 *\/ { OP_ReadCookie, 0, 1, 0}, \/* 1 *\/ { OP_ResultRow, 1, 1, 0} }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p3 = iCookie; sqlite3VdbeReusable(v); } } break; #endif \/* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS *\/ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS \/* ** PRAGMA compile_options ** ** Return the names of all compile-time options used in this build, ** one option per row. *\/ case PragTyp_COMPILE_OPTIONS: { int i = 0; const char *zOpt; pParse->nMem = 1; while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ sqlite3VdbeLoadString(v, 1, zOpt); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } sqlite3VdbeReusable(v); } break; #endif \/* SQLITE_OMIT_COMPILEOPTION_DIAGS *\/ #ifndef SQLITE_OMIT_WAL \/* ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate ** ** Checkpoint the database. *\/ case PragTyp_WAL_CHECKPOINT: { int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); int eMode = SQLITE_CHECKPOINT_PASSIVE; if( zRight ){ if( sqlite3StrICmp(zRight, \"full\")==0 ){ eMode = SQLITE_CHECKPOINT_FULL; }else if( sqlite3StrICmp(zRight, \"restart\")==0 ){ eMode = SQLITE_CHECKPOINT_RESTART; }else if( sqlite3StrICmp(zRight, \"truncate\")==0 ){ eMode = SQLITE_CHECKPOINT_TRUNCATE; } } pParse->nMem = 3; sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } break; \/* ** PRAGMA wal_autocheckpoint ** PRAGMA wal_autocheckpoint = N ** ** Configure a database connection to automatically checkpoint a database ** after accumulating N frames in the log. Or query for the current value ** of N. *\/ case PragTyp_WAL_AUTOCHECKPOINT: { if( zRight ){ sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); } returnSingleInt(v, db->xWalCallback==sqlite3WalDefaultHook ? SQLITE_PTR_TO_INT(db->pWalArg) : 0); } break; #endif \/* ** PRAGMA shrink_memory ** ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database ** connection on which it is invoked to free up as much memory as it ** can, by calling sqlite3_db_release_memory(). *\/ case PragTyp_SHRINK_MEMORY: { sqlite3_db_release_memory(db); break; } \/* ** PRAGMA optimize ** PRAGMA optimize(MASK) ** PRAGMA schema.optimize ** PRAGMA schema.optimize(MASK) ** ** Attempt to optimize the database. All schemas are optimized in the first ** two forms, and only the specified schema is optimized in the latter two. ** ** The details of optimizations performed by this pragma are expected ** to change and improve over time. Applications should anticipate that ** this pragma will perform new optimizations in future releases. ** ** The optional argument is a bitmask of optimizations to perform: ** ** 0x0001 Debugging mode. Do not actually perform any optimizations ** but instead return one line of text for each optimization ** that would have been done. Off by default. ** ** 0x0002 Run ANALYZE on tables that might benefit. On by default. ** See below for additional information. ** ** 0x0004 (Not yet implemented) Record usage and performance ** information from the current session in the ** database file so that it will be available to \"optimize\" ** pragmas run by future database connections. ** ** 0x0008 (Not yet implemented) Create indexes that might have ** been helpful to recent queries ** ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all ** of the optimizations listed above except Debug Mode, including new ** optimizations that have not yet been invented. If new optimizations are ** ever added that should be off by default, those off-by-default ** optimizations will have bitmasks of 0x10000 or larger. ** ** DETERMINATION OF WHEN TO RUN ANALYZE ** ** In the current implementation, a table is analyzed if only if all of ** the following are true: ** ** (1) MASK bit 0x02 is set. ** ** (2) The query planner used sqlite_stat1-style statistics for one or ** more indexes of the table at some point during the lifetime of ** the current connection. ** ** (3) One or more indexes of the table are currently unanalyzed OR ** the number of rows in the table has increased by 25 times or more ** since the last time ANALYZE was run. ** ** The rules for when tables are analyzed are likely to change in ** future releases. *\/ case PragTyp_OPTIMIZE: { int iDbLast; \/* Loop termination point for the schema loop *\/ int iTabCur; \/* Cursor for a table whose size needs checking *\/ HashElem *k; \/* Loop over tables of a schema *\/ Schema *pSchema; \/* The current schema *\/ Table *pTab; \/* A table in the schema *\/ Index *pIdx; \/* An index of the table *\/ LogEst szThreshold; \/* Size threshold above which reanalysis is needd *\/ char *zSubSql; \/* SQL statement for the OP_SqlExec opcode *\/ u32 opMask; \/* Mask of operations to perform *\/ if( zRight ){ opMask = (u32)sqlite3Atoi(zRight); if( (opMask & 0x02)==0 ) break; }else{ opMask = 0xfffe; } iTabCur = pParse->nTab++; for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){ if( iDb==1 ) continue; sqlite3CodeVerifySchema(pParse, iDb); pSchema = db->aDb[iDb].pSchema; for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ pTab = (Table*)sqliteHashData(k); \/* If table pTab has not been used in a way that would benefit from ** having analysis statistics during the current session, then skip it. ** This also has the effect of skipping virtual tables and views *\/ if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue; \/* Reanalyze if the table is 25 times larger than the last analysis *\/ szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 ); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( !pIdx->hasStat1 ){ szThreshold = 0; \/* Always analyze if any index lacks statistics *\/ break; } } if( szThreshold ){ sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold); VdbeCoverage(v); } zSubSql = sqlite3MPrintf(db, \"ANALYZE \\\"%w\\\".\\\"%w\\\"\", db->aDb[iDb].zDbSName, pTab->zName); if( opMask & 0x01 ){ int r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC); sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1); }else{ sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC); } } } sqlite3VdbeAddOp0(v, OP_Expire); break; } \/* ** PRAGMA busy_timeout ** PRAGMA busy_timeout = N ** ** Call sqlite3_busy_timeout(db, N). Return the current timeout value ** if one is set. If no busy handler or a different busy handler is set ** then 0 is returned. Setting the busy_timeout to 0 or negative ** disables the timeout. *\/ \/*case PragTyp_BUSY_TIMEOUT*\/ default: { assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT ); if( zRight ){ sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); } returnSingleInt(v, db->busyTimeout); break; } \/* ** PRAGMA soft_heap_limit ** PRAGMA soft_heap_limit = N ** ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the ** sqlite3_soft_heap_limit64() interface with the argument N, if N is ** specified and is a non-negative integer. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always ** returns the same integer that would be returned by the ** sqlite3_soft_heap_limit64(-1) C-language function. *\/ case PragTyp_SOFT_HEAP_LIMIT: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ sqlite3_soft_heap_limit64(N); } returnSingleInt(v, sqlite3_soft_heap_limit64(-1)); break; } \/* ** PRAGMA hard_heap_limit ** PRAGMA hard_heap_limit = N ** ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap ** limit. The hard heap limit can be activated or lowered by this ** pragma, but not raised or deactivated. Only the ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate ** the hard heap limit. This allows an application to set a heap limit ** constraint that cannot be relaxed by an untrusted SQL script. *\/ case PragTyp_HARD_HEAP_LIMIT: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1); if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N); } returnSingleInt(v, sqlite3_hard_heap_limit64(-1)); break; } \/* ** PRAGMA threads ** PRAGMA threads = N ** ** Configure the maximum number of worker threads. Return the new ** maximum, which might be less than requested. *\/ case PragTyp_THREADS: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK && N>=0 ){ sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff)); } returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1)); break; } #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) \/* ** Report the current state of file logs for all databases *\/ case PragTyp_LOCK_STATUS: { static const char *const azLockName[] = { \"unlocked\", \"shared\", \"reserved\", \"pending\", \"exclusive\" }; int i; pParse->nMem = 2; for(i=0; inDb; i++){ Btree *pBt; const char *zState = \"unknown\"; int j; if( db->aDb[i].zDbSName==0 ) continue; pBt = db->aDb[i].pBt; if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ zState = \"closed\"; }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ zState = azLockName[j]; } sqlite3VdbeMultiLoad(v, 1, \"ss\", db->aDb[i].zDbSName, zState); } break; } #endif #ifdef SQLITE_HAS_CODEC \/* Pragma iArg ** ---------- ------ ** key 0 ** rekey 1 ** hexkey 2 ** hexrekey 3 ** textkey 4 ** textrekey 5 *\/ case PragTyp_KEY: { if( zRight ){ char zBuf[40]; const char *zKey = zRight; int n; if( pPragma->iArg==2 || pPragma->iArg==3 ){ u8 iByte; int i; for(i=0, iByte=0; iiArg<4 ? sqlite3Strlen30(zRight) : -1; } if( (pPragma->iArg & 1)==0 ){ rc = sqlite3_key_v2(db, zDb, zKey, n); }else{ rc = sqlite3_rekey_v2(db, zDb, zKey, n); } if( rc==SQLITE_OK && n!=0 ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"ok\", SQLITE_STATIC); returnSingleText(v, \"ok\"); } } break; } #endif #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){ #ifdef SQLITE_HAS_CODEC if( sqlite3StrNICmp(zRight, \"see-\", 4)==0 ){ sqlite3_activate_see(&zRight[4]); } #endif #ifdef SQLITE_ENABLE_CEROD if( sqlite3StrNICmp(zRight, \"cerod-\", 6)==0 ){ sqlite3_activate_cerod(&zRight[6]); } #endif } break; #endif } \/* End of the PRAGMA switch *\/ \/* The following block is a no-op unless SQLITE_DEBUG is defined. Its only ** purpose is to execute assert() statements to verify that if the ** PragFlg_NoColumns1 flag is set and the caller specified an argument ** to the PRAGMA, the implementation has not added any OP_ResultRow ** instructions to the VM. *\/ if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){ sqlite3VdbeVerifyNoResultRow(v); } pragma_out: sqlite3DbFree(db, zLeft); sqlite3DbFree(db, zRight); }","output":{"is_vulnerable":"True","vulnerability_types":["Improper Check for Unusual or Exceptional Conditions"],"explanation":"pragma.c in SQLite through 3.30.1 mishandles NOT NULL in an integrity_check PRAGMA command in certain cases of generated columns.","severity_level":"NoInfo","cwe":"CWE-754","cve":"CVE-2019-19646"}} -{"idx":456901,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { char s[2]; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MaxTextExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MaxTextExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; \/* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; *\/ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; property=(const char *) NULL; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->magick= %s\",image_info->magick); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register PixelPacket *r; ExceptionInfo *exception; exception=(&image->exception); if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->matte == MagickFalse))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ number_opaque = (int) image->colors; if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; else ping_have_color=MagickTrue; ping_have_non_bw=MagickFalse; if (image->matte != MagickFalse) { number_transparent = 2; number_semitransparent = 1; } else { number_transparent = 0; number_semitransparent = 0; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; if (image->depth != GetImageDepth(image,&image->exception)) (void) SetImageDepth(image,image->depth); for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->matte is MagickFalse, we ignore the opacity channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ ExceptionInfo *exception; int n; PixelPacket opaque[260], semitransparent[260], transparent[260]; register IndexPacket *indexes; register const PixelPacket *s, *q; register PixelPacket *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->matte=%.20g\",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,opacity)\"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } exception=(&image->exception); image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte == MagickFalse || GetPixelOpacity(q) == OpaqueOpacity) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelRGB(q, opaque); opaque[0].opacity=OpaqueOpacity; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(q, opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelRGB(q, opaque+i); opaque[i].opacity=OpaqueOpacity; } } } else if (q->opacity == TransparentOpacity) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelRGBO(q, transparent); ping_trans_color.red= (unsigned short) GetPixelRed(q); ping_trans_color.green= (unsigned short) GetPixelGreen(q); ping_trans_color.blue= (unsigned short) GetPixelBlue(q); ping_trans_color.gray= (unsigned short) GetPixelRed(q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(q, transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelRGBO(q, transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelRGBO(q, semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(q, semitransparent+i) && GetPixelOpacity(q) == semitransparent[i].opacity) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelRGBO(q, semitransparent+i); } } } q++; } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != GetPixelGreen(s) || GetPixelRed(s) != GetPixelBlue(s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s++; } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != 0 && GetPixelRed(s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s++; } } } } } if (image_colors < 257) { PixelPacket colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->matte == MagickFalse || image->colormap[i].opacity == GetPixelOpacity(q)) && image->colormap[i].red == GetPixelRed(q) && image->colormap[i].green == GetPixelGreen(q) && image->colormap[i].blue == GetPixelBlue(q)) { SetPixelIndex(indexes+x,i); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,opacity)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) > TransparentOpacity\/2) { SetPixelOpacity(r,TransparentOpacity); SetPixelRgb(r,&image->background_color); } else SetPixelOpacity(r,OpaqueOpacity); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].opacity = (image->colormap[i].opacity > TransparentOpacity\/2 ? TransparentOpacity : OpaqueOpacity); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR04PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR03PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR02PixelBlue(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 && GetPixelOpacity(r) == OpaqueOpacity) { SetPixelRed(r,ScaleCharToQuantum(0x24)); } r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { ExceptionInfo *exception; register const PixelPacket *q; exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (q->opacity != TransparentOpacity && (unsigned short) GetPixelRed(q) == ping_trans_color.red && (unsigned short) GetPixelGreen(q) == ping_trans_color.green && (unsigned short) GetPixelBlue(q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q++; } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->matte; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",image->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->x_resolution != 0) && (image->y_resolution != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->x_resolution+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->y_resolution+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->x_resolution; ping_pHYs_y_resolution=(png_uint_32) image->y_resolution; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorMatteType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteMatteType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } (void) old_bit_depth; image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, image->colormap))) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) (255- ScaleQuantumToChar(image->colormap[i].opacity)); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)*(ScaleQuantumToShort((Quantum) GetPixelLuma(image,&image->background_color)))+.5); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_background.index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_background.gray is %d\", (int) ping_background.gray); } ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This is addressed by using \"-define png:compression-strategy\", etc., which takes precedence over -quality. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->matte == MagickFalse) { \/* Add an opaque matte channel *\/ image->matte = MagickTrue; (void) SetImageOpacity(image,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { if (mng_info->have_write_global_plte && matte == MagickFalse) { png_set_PLTE(ping,ping_info,NULL,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up empty PLTE chunk\"); } else png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(const png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } else #endif { if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } if (ping_exclude_zCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXT chunk with uuencoded ICC\"); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk with %s profile\",name); name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\"); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; (void) ping_have_blob; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(ping_pixels,0,rowbytes*sizeof(*ping_pixels)); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { \/* Palette, Bilevel, or Opaque Monochrome *\/ QuantumType quantum_type; register const PixelPacket *p; quantum_type=RedQuantum; if (mng_info->IsPalette) { quantum_type=GrayQuantum; if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) quantum_type=IndexQuantum; } SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,ping_pixels,&image->exception); if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\",pass); p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(image,\"png:bit-depth-written\",s); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":344104,"input":"void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, \/* EOS M *\/ { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, { 6096, 4056, 72, 34, 0, 0 }, \/* EOS M3 *\/ { 8896, 5920, 160, 64, 0, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, \"EOS-1D\" }, { 0x167, \"EOS-1DS\" }, { 0x168, \"EOS 10D\" }, { 0x169, \"EOS-1D Mark III\" }, { 0x170, \"EOS 300D\" }, { 0x174, \"EOS-1D Mark II\" }, { 0x175, \"EOS 20D\" }, { 0x176, \"EOS 450D\" }, { 0x188, \"EOS-1Ds Mark II\" }, { 0x189, \"EOS 350D\" }, { 0x190, \"EOS 40D\" }, { 0x213, \"EOS 5D\" }, { 0x215, \"EOS-1Ds Mark III\" }, { 0x218, \"EOS 5D Mark II\" }, { 0x232, \"EOS-1D Mark II N\" }, { 0x234, \"EOS 30D\" }, { 0x236, \"EOS 400D\" }, { 0x250, \"EOS 7D\" }, { 0x252, \"EOS 500D\" }, { 0x254, \"EOS 1000D\" }, { 0x261, \"EOS 50D\" }, { 0x269, \"EOS-1D X\" }, { 0x270, \"EOS 550D\" }, { 0x281, \"EOS-1D Mark IV\" }, { 0x285, \"EOS 5D Mark III\" }, { 0x286, \"EOS 600D\" }, { 0x287, \"EOS 60D\" }, { 0x288, \"EOS 1100D\" }, { 0x289, \"EOS 7D Mark II\" }, { 0x301, \"EOS 650D\" }, { 0x302, \"EOS 6D\" }, { 0x324, \"EOS-1D C\" }, { 0x325, \"EOS 70D\" }, { 0x326, \"EOS 700D\" }, { 0x327, \"EOS 1200D\" }, { 0x331, \"EOS M\" }, { 0x335, \"EOS M2\" }, { 0x374, \"EOS M3\"}, \/* temp *\/ { 0x346, \"EOS 100D\" }, { 0x347, \"EOS 760D\" }, { 0x382, \"EOS 5DS\" }, { 0x393, \"EOS 750D\" }, { 0x401, \"EOS 5DS R\" }, }, sonique[] = { { 0x002, \"DSC-R1\" }, { 0x100, \"DSLR-A100\" }, { 0x101, \"DSLR-A900\" }, { 0x102, \"DSLR-A700\" }, { 0x103, \"DSLR-A200\" }, { 0x104, \"DSLR-A350\" }, { 0x105, \"DSLR-A300\" }, { 0x106, \"DSLR-A900\" }, { 0x107, \"DSLR-A380\" }, { 0x108, \"DSLR-A330\" }, { 0x109, \"DSLR-A230\" }, { 0x10a, \"DSLR-A290\" }, { 0x10d, \"DSLR-A850\" }, { 0x10e, \"DSLR-A850\" }, { 0x111, \"DSLR-A550\" }, { 0x112, \"DSLR-A500\" }, { 0x113, \"DSLR-A450\" }, { 0x116, \"NEX-5\" }, { 0x117, \"NEX-3\" }, { 0x118, \"SLT-A33\" }, { 0x119, \"SLT-A55V\" }, { 0x11a, \"DSLR-A560\" }, { 0x11b, \"DSLR-A580\" }, { 0x11c, \"NEX-C3\" }, { 0x11d, \"SLT-A35\" }, { 0x11e, \"SLT-A65V\" }, { 0x11f, \"SLT-A77V\" }, { 0x120, \"NEX-5N\" }, { 0x121, \"NEX-7\" }, { 0x122, \"NEX-VG20E\"}, { 0x123, \"SLT-A37\" }, { 0x124, \"SLT-A57\" }, { 0x125, \"NEX-F3\" }, { 0x126, \"SLT-A99V\" }, { 0x127, \"NEX-6\" }, { 0x128, \"NEX-5R\" }, { 0x129, \"DSC-RX100\" }, { 0x12a, \"DSC-RX1\" }, { 0x12b, \"NEX-VG900\" }, { 0x12c, \"NEX-VG30E\" }, { 0x12e, \"ILCE-3000\" }, { 0x12f, \"SLT-A58\" }, { 0x131, \"NEX-3N\" }, { 0x132, \"ILCE-7\" }, { 0x133, \"NEX-5T\" }, { 0x134, \"DSC-RX100M2\" }, { 0x135, \"DSC-RX10\" }, { 0x136, \"DSC-RX1R\" }, { 0x137, \"ILCE-7R\" }, { 0x138, \"ILCE-6000\" }, { 0x139, \"ILCE-5000\" }, { 0x13d, \"DSC-RX100M3\" }, { 0x13e, \"ILCE-7S\" }, { 0x13f, \"ILCA-77M2\" }, { 0x153, \"ILCE-5100\" }, { 0x154, \"ILCE-7M2\" }, { 0x155, \"DSC-RX100M4\" }, { 0x156, \"DSC-RX10M2\" }, { 0x15a, \"ILCE-QX1\" }, { 0x15b, \"ILCE-7RM2\" }, }; static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-080C\" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-145C\" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-201C\" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-510C\" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-510C\",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,\"AVT\",\"F-510C\" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,\"AVT\",\"F-510C\",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,\"AVT\",\"F-810C\" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,\"AgfaPhoto\",\"DC-833m\" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,\"Alcatel\",\"5035D\" }, \/\/ Android Raw dumps id start \/\/ File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 16424960,4208,3120, 0, 0, 0, 0, 1,0x16,0,0,\"Sony\",\"IMX135-mipi 13mp\" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,\"Sony\",\"IMX135-QCOM\" }, { 10223360,2608,1960, 0, 0, 0, 0, 1,0x94,0,0,\"Sony\",\"IMX072-mipi\" }, { 5107712,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,\"HTC\",\"UltraPixel\" }, { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,\"Samsung\",\"S3\" }, { 10223363,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,\"Samsung\",\"GalaxyNexus\" }, \/\/ Android Raw dumps id end { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,\"Baumer\",\"TXG14\",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,\"Canon\",\"PowerShot SD300\" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,\"Canon\",\"PowerShot A460\" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,\"Canon\",\"PowerShot A610\" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,\"Canon\",\"PowerShot A530\" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,\"Canon\",\"PowerShot S3 IS\" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,\"Canon\",\"PowerShot A620\" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,\"Canon\",\"PowerShot A470\" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,\"Canon\",\"PowerShot A720 IS\" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,\"Canon\",\"PowerShot A630\" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,\"Canon\",\"PowerShot A640\" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,\"Canon\",\"PowerShot A650\" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,\"Canon\",\"PowerShot SX110 IS\" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,\"Canon\",\"PowerShot SX120 IS\" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,\"Canon\",\"PowerShot SX20 IS\" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,\"Canon\",\"PowerShot SX220 HS\" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,\"Canon\",\"PowerShot SX30 IS\" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,\"Canon\",\"PowerShot A3300 IS\" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,\"Casio\",\"QV-2000UX\" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,\"Casio\",\"QV-3*00EX\" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,\"Casio\",\"QV-5700\" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,\"Casio\",\"EX-Z60\" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,\"Casio\",\"EX-S20\" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,\"Casio\",\"EX-S100\" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,\"Casio\",\"QV-R41\" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,\"Casio\",\"EX-P505\" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,\"Casio\",\"QV-R51\" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,\"Casio\",\"EX-Z50\" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,\"Casio\",\"EX-Z500\" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,\"Casio\",\"EX-Z55\" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,\"Casio\",\"EX-P600\" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,\"Casio\",\"EX-Z750\" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,\"Casio\",\"EX-Z75\" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,\"Casio\",\"EX-P700\" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,\"Casio\",\"EX-Z850\" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,\"Casio\",\"EX-Z8\" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,\"Casio\",\"EX-Z1050\" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,\"Casio\",\"EX-ZR100\" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,\"Casio\",\"QV-4000\" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,\"Creative\",\"PC-CAM 600\" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,\"DJI\" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,\"Matrix\" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,\"Foculus\",\"531C\" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,\"Generic\" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,\"Kodak\",\"DC20\" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,\"Kodak\",\"DC20\" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,\"Kodak\",\"DCS200\" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,\"Kodak\",\"C330\" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,\"Kodak\",\"C330\",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,\"Kodak\",\"C330\" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,\"Kodak\",\"C330\" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,\"Kodak\",\"C603\" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,\"Kodak\",\"C603\",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,\"Kodak\",\"C603\" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,\"Kodak\",\"C603\" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,\"Kodak\",\"12MP\" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,\"Kodak\",\"12MP\",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,\"Kodak\",\"12MP\" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,\"Kodak\",\"KAI-0340\" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,\"Lenovo\",\"A820\" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,\"Micron\",\"2010\",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,\"Minolta\",\"RD175\",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,\"Nikon\",\"E900\" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,\"Nikon\",\"E950\" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,\"Nikon\",\"E2100\" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,\"Nikon\",\"E990\" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,\"Nikon\",\"E3700\" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,\"Nikon\",\"E4500\" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,\"Nikon\",\"E4300\" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,\"Nikon\",\"E5000\" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,\"Nikon\",\"COOLPIX S6\" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,\"Olympus\",\"C770UZ\" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,\"Pentax\",\"Optio S\" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,\"Pentax\",\"Optio S\" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,\"Pentax\",\"Optio S4\" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,\"Pentax\",\"Optio 750Z\" }, { 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,\"Photron\",\"BC2-HD\" }, { 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,\"Photron\",\"BC2-HD\",8 }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,\"Pixelink\",\"A782\" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,\"RoverShot\",\"3320AF\" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,\"ST Micro\",\"STV680 VGA\" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,\"Samsung\",\"S85\" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,\"Samsung\",\"S85\" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,\"Samsung\",\"WB550\" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,\"Samsung\",\"WB550\" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,\"Sinar\",\"\",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,\"Sinar\",\"\",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,\"Sinar\",\"\",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,\"Sony\",\"XCD-SX910CR\" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,\"Sony\",\"XCD-SX910CR\" }, }; static const char *corp[] = { \"AgfaPhoto\", \"Canon\", \"Casio\", \"Epson\", \"Fujifilm\", \"Mamiya\", \"Minolta\", \"Motorola\", \"Kodak\", \"Konica\", \"Leica\", \"Nikon\", \"Nokia\", \"Olympus\", \"Pentax\", \"Phase One\", \"Ricoh\", \"Samsung\", \"Sigma\", \"Sinar\", \"Sony\" }; char head[32], *cp; int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; tiff_flip = flip = filters = UINT_MAX; \/* unknown *\/ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); fread (head, 1, 32, ifp); fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)\"MMMM\", 4)) || (cp = (char *) memmem (head, 32, (char*)\"IIII\", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,\"HEAPCCDR\",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,\"\\xff\\xd8\\xff\\xe1\",4) && !memcmp (head+6,\"Exif\",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,\"ARECOYK\",7)) { strcpy (make, \"Contax\"); strcpy (model,\"N Digital\"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = powf64(2.0f, (((float)get4())\/8.0f)) \/ 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek (ifp, 88, SEEK_SET); aperture = powf64(2.0f, ((float)get4())\/16.0f); fseek (ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek (ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4())\/16.0f); fseek (ifp, 124, SEEK_SET); fread(imgdata.lens.makernotes.Lens, 32, 1, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp (head, \"PXN\")) { strcpy (make, \"Logitech\"); strcpy (model,\"Fotoman Pixtura\"); } else if (!strcmp (head, \"qktk\")) { strcpy (make, \"Apple\"); strcpy (model,\"QuickTake 100\"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, \"qktn\")) { strcpy (make, \"Apple\"); strcpy (model,\"QuickTake 150\"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,\"FUJIFILM\",8)) { fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4()) && 1; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,\"RIFF\",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,\"ftypqt \",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,\"\\0\\001\\0\\001\\0@\",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,\"NOKIARAW\",8)) { strcpy (make, \"NOKIA\"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); switch (tiff_bps = i*8 \/ (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i \/ (width * tiff_bps\/8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp (head,\"ARRI\",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, \"ARRI\"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,\"XPDS\",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,\"RED1\",4)) { strcpy (make, \"Red\"); strcpy (model,\"One\"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1\/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,\"DSC-Image\",9)) parse_rollei(); else if (!memcmp (head,\"PWAD\",4)) parse_sinar_ia(); else if (!memcmp (head,\"\\0MRM\",4)) parse_minolta(0); else if (!memcmp (head,\"FOVb\",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!imgdata.params.force_foveon_x3f) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,\"CI\",2)) parse_cine(); if(make[0] == 0) for (zero_fsize=i=0; i < sizeof table \/ sizeof *table; i++) if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, \"Canon\",5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 \/ (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)\/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); if (!(strncmp(model,\"ov\",2) && strncmp(model,\"RP_OV\",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,\"BRCMn\")) { strcpy (make, \"OmniVision\"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; } else is_raw = 0; } for (i=0; i < sizeof corp \/ sizeof *corp; i++) if (strcasestr (make, corp[i])) \/* Simplify company names *\/ strcpy (make, corp[i]); if ((!strncmp(make,\"Kodak\",5) || !strncmp(make,\"Leica\",5)) && ((cp = strcasestr(model,\" DIGITAL CAMERA\")) || (cp = strstr(model,\"FILE VERSION\")))) *cp = 0; if (!strncasecmp(model,\"PENTAX\",6)) strcpy (make, \"Pentax\"); cp = make + strlen(make); \/* Remove trailing spaces *\/ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; i = strlen(make); \/* Remove make from model *\/ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,\"FinePix \",8)) strcpy (model, model+8); if (!strncmp (model,\"Digital Camera \",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) \/* Pentax K10D and Samsung GX10 *\/ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) \/* Pentax K20D and Samsung GX20 *\/ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,\"K-r\") || !strcmp(model,\"K-x\"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,\"K-5\",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 4736 && !strcmp(model,\"K-7\")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,\"K-3 II\")) { left_margin = 4; width = 6040; } if (width == 6080 && !strcmp(model,\"K-3\")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,\"645D\")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) \/* Ricoh GX200 *\/ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw = tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: \/* Compression not set, assuming uncompressed *\/ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, \"Canon\",5) && unique_id) { for (i = 0; i < sizeof unique \/ sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, \"Sony\",4) && unique_id) { for (i = 0; i < sizeof sonique \/ sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make,\"Canon\",5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon \/ sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make,\"Canon\",5) && unique_id) { for (i=0; i < sizeof unique \/ sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff (\"Canon\", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strncasecmp(make,\"Sony\",4) && unique_id) { for (i=0; i < sizeof sonique \/ sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff (\"Sony\", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strncmp(make,\"Nikon\",5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } \/* Set parameters based on camera name (for non-DNG files). *\/ if (!strcmp(model,\"KAI-0340\") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,\"C603\"); } if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!imgdata.params.force_foveon_x3f) simple_coeff(0); #endif } else if (!strncmp(make,\"Canon\",5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height,width); SWAP(raw_height,raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,\"PowerShot 600\")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,\"PowerShot A5\") || !strcmp(model,\"PowerShot A5 Zoom\")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256\/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,\"PowerShot A50\")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,\"PowerShot Pro70\")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,\"PowerShot Pro90 IS\") || !strcmp(model,\"PowerShot G1\")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,\"PowerShot A610\")) { if (canon_s2is()) strcpy (model+10, \"S2 IS\"); } else if (!strcmp(model,\"PowerShot SX220 HS\")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,\"PowerShot S120\")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,\"PowerShot G16\")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,\"PowerShot SX50 HS\")) { top_margin = 17; } else if (!strcmp(model,\"EOS D2000C\")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,\"D1\")) { cam_mul[0] *= 256\/527.0; cam_mul[2] *= 256\/317.0; } else if (!strcmp(model,\"D1X\")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,\"D40X\") || !strcmp(model,\"D60\") || !strcmp(model,\"D80\") || !strcmp(model,\"D3000\")) { height -= 3; width -= 4; } else if (!strcmp(model,\"D3\") || !strcmp(model,\"D3S\") || !strcmp(model,\"D700\")) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"D3100\")) { width -= 28; left_margin = 6; } else if (!strcmp(model,\"D5000\") || !strcmp(model,\"D90\")) { width -= 42; } else if (!strcmp(model,\"D5100\") || !strcmp(model,\"D7000\") || !strcmp(model,\"COOLPIX A\")) { width -= 44; } else if (!strcmp(model,\"D3200\") || !strncmp(model,\"D6\",2) || !strncmp(model,\"D800\",4)) { width -= 46; } else if (!strcmp(model,\"D4\") || !strcmp(model,\"Df\")) { width -= 52; left_margin = 2; } else if (!strncmp(model,\"D40\",3) || !strncmp(model,\"D50\",3) || !strncmp(model,\"D70\",3)) { width--; } else if (!strcmp(model,\"D100\")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,\"D200\")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,\"D2H\",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,\"D2X\",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,\"D300\",4)) { width -= 32; } else if (!strncmp(make,\"Nikon\",5) && raw_width == 4032) { if(!strcmp(model,\"COOLPIX P7700\")) { adobe_coeff (\"Nikon\",\"COOLPIX P7700\"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,\"COOLPIX P7800\")) { adobe_coeff (\"Nikon\",\"COOLPIX P7800\"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,\"COOLPIX P340\")) load_flags=0; } else if (!strncmp(model,\"COOLPIX P\",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && iso_speed >= 400) black = 255; } else if (!strncmp(model,\"1 \",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, \"E995\"); if (strcmp(model,\"E995\")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,\"E2500\"); if (!strcmp(model,\"E2500\")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,\"Optio 33WR\")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, \"Minolta\"); strcpy (model,\"DiMAGE Z2\"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, \"ISG\"); model[0] = 0; } } else if (!strncmp(make,\"Fujifilm\",8)) { if (!strcmp(model+7,\"S2Pro\")) { strcpy (model,\"S2Pro\"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (!strcmp(model,\"HS50EXR\") || !strcmp(model,\"F900EXR\")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,\"S5500\")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) ((char *)xtrans)[c] = xtrans_abs[(c\/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,\"KD-400Z\")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,\"KD-510Z\")) { goto konica_510z; } else if (!strncasecmp(make,\"Minolta\",7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,\"DiMAGE A\",8)) { if (!strcmp(model,\"DiMAGE A200\")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,\"ALPHA\",5) || !strncmp(model,\"DYNAX\",5) || !strncmp(model,\"MAXXUM\",6)) { sprintf (model+20, \"DYNAX %-10s\", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,\"DiMAGE G\",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,\"*ist D\")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,\"*ist DS\")) { height -= 2; } else if (!strncmp(make,\"Samsung\",7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make,\"Samsung\",7) && !strcmp(model,\"NX3000\")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strncmp(make,\"Samsung\",7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make,\"Samsung\",7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make,\"Samsung\",7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make,\"Samsung\",7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model,\"EX1\")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,\"WB2000\")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,\"WB550\")) { strcpy (model, \"WB550\"); } else if (!strcmp(model,\"EX2F\")) { height = 3045; width = 4070; top_margin = 3; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,\"STV680 VGA\")) { black = 16; } else if (!strcmp(model,\"N95\")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,\"640x480\")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strncmp(make,\"Hasselblad\",10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strncasecmp(model,\"H3D\",3)) { adobe_coeff(\"Hasselblad\",\"H3DII-39\"); strcpy(model,\"H3DII-39\"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff(\"Hasselblad\",\"H4D-40\"); strcpy(model,\"H4D-40\"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff(\"Hasselblad\",\"H4D-60\"); strcpy(model,\"H4D-60\"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,\"H3DII-60\"); } } else if (raw_width == 4090) { strcpy (model, \"V96C\"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strncasecmp(model,\"H5D\",3)) { \/* H5D 50*\/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,\"H5D-50\"); } else if(!strncasecmp(model,\"H3D\",3)) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff(\"Hasselblad\",\"H3D-50\"); strcpy(model,\"H3D-50\"); } } else if (raw_width == 8374 && raw_height == 6304) { \/* H5D 50c*\/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,\"H5D-50c\"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make,\"Sinar\",5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make,\"Leaf\",4)) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, \"RBTG\"); strcpy (model, \"CatchLight\"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, \"DCB2\"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, \"Cantare\"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, \"Valeo 6\"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, \"Valeo 6\"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make,\"Leica\",5) || !strncmp(make,\"Panasonic\",9)) { if (raw_width > 0&& ((flen - data_offset) \/ (raw_width*8\/7) == raw_height) ) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana \/ sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) \"\\x94\\x61\\x49\\x16\" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,\"C770UZ\")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make,\"Olympus\",7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,\"E-300\") || !strcmp(model,\"E-500\")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,\"STYLUS1\")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,\"E-330\")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,\"SP550UZ\")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } } else if (!strcmp(model,\"N Digital\")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,\"DSC-F828\")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, \"RGBE\"); } else if (!strcmp(model,\"DSC-V3\")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make,\"Sony\",4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make,\"Sony\",4) && raw_width == 4288) { width -= 32; } else if (!strncmp(make,\"Sony\",4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make,\"Sony\",4) && raw_width == 5504) { \/\/ ILCE-3000\/\/5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make,\"Sony\",4) && raw_width == 6048) { width -= 24; if (strstr(model,\"RX1\") || strstr(model,\"A99\")) width -= 6; } else if (!strncmp(make,\"Sony\",4) && raw_width == 7392) { width -= 30; } else if (!strcmp(model,\"DSLR-A100\")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,\"DSLR-A350\")) { height -= 4; } else if (!strcmp(model,\"PIXL\")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,\"C603\") || !strcmp(model,\"C330\") || !strcmp(model,\"12MP\")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,\"C330\") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,\"EasyShare\",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make,\"Kodak\",5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,\"NC2000\",6) || !strncmp(model,\"EOSDCS\",6) || !strncmp(model,\"DCS4\",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,\"DCS460A\")) goto bw; } else if (!strcmp(model,\"DCS660M\")) { black = 214; goto bw; } else if (!strcmp(model,\"DCS760M\")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,\"20X\")) strcpy (cdesc, \"MYCY\"); if (strstr(model,\"DC25\")) { strcpy (model, \"DC25\"); data_offset = 15424; } if (!strncmp(model,\"DC2\",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, \"DC290\", 5)) iso_speed = 100; if (!strncmp(model, \"DC280\", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) \/ (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) \/ (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,\"40\")) { strcpy (model, \"DC40\"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,\"DC50\")) { strcpy (model, \"DC50\"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,\"DC120\")) { strcpy (model, \"DC120\"); height = 976; width = 848; iso_speed=160; pixel_aspect = height\/0.75\/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,\"DCS200\")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,\"Fotoman Pixtura\")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,\"QuickTake\",9)) { if (head[5]) strcpy (model+10, \"200\"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strncmp(make,\"Rollei\",6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,\"GRAS-50S5C\")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,\"BB-500CL\")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,\"BB-500GE\")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,\"SVS625CL\")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } \/* Early reject for damaged images *\/ if (!load_raw || height < 22 || width < 22 || tiff_bps > 16 || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, \"%dx%d\", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: \/* Early reject for damaged images *\/ if (!load_raw || height < 22 || width < 22 || tiff_bps > 16 || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if ((use_camera_matrix & (use_camera_wb || dng_version)) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff (\"Apple\",\"Quicktake\"); if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || tiff_bps > 16 || tiff_samples > 6 || colors > 4) is_raw = 0; if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_(\"%s: You must link dcraw with %s!!\\n\"), ifname, \"libjasper\"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_(\"%s: You must link dcraw with %s!!\\n\"), ifname, \"libjpeg\"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? \"RGBG\":\"GMCY\"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":186559,"input":"static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) { char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL; PGconn *pgsql; smart_str str = {0}; zval *args; uint32_t i; int connect_type = 0; PGresult *pg_result; args = (zval *)safe_emalloc(ZEND_NUM_ARGS(), sizeof(zval), 0); if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5 || zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) { efree(args); WRONG_PARAM_COUNT; } smart_str_appends(&str, \"pgsql\"); for (i = 0; i < ZEND_NUM_ARGS(); i++) { \/* make sure that the PGSQL_CONNECT_FORCE_NEW bit is not part of the hash so that subsequent connections * can re-use this connection. Bug #39979 *\/ if (i == 1 && ZEND_NUM_ARGS() == 2 && Z_TYPE(args[i]) == IS_LONG) { if (Z_LVAL(args[1]) == PGSQL_CONNECT_FORCE_NEW) { continue; } else if (Z_LVAL(args[1]) & PGSQL_CONNECT_FORCE_NEW) { smart_str_append_long(&str, Z_LVAL(args[1]) ^ PGSQL_CONNECT_FORCE_NEW); } } convert_to_string_ex(&args[i]); smart_str_appendc(&str, '_'); smart_str_appendl(&str, Z_STRVAL(args[i]), Z_STRLEN(args[i])); } smart_str_0(&str); if (ZEND_NUM_ARGS() == 1) { \/* new style, using connection string *\/ connstring = Z_STRVAL(args[0]); } else if (ZEND_NUM_ARGS() == 2 ) { \/* Safe to add conntype_option, since 2 args was illegal *\/ connstring = Z_STRVAL(args[0]); convert_to_long_ex(&args[1]); connect_type = (int)Z_LVAL(args[1]); } else { host = Z_STRVAL(args[0]); port = Z_STRVAL(args[1]); dbname = Z_STRVAL(args[ZEND_NUM_ARGS()-1]); switch (ZEND_NUM_ARGS()) { case 5: tty = Z_STRVAL(args[3]); \/* fall through *\/ case 4: options = Z_STRVAL(args[2]); break; } } efree(args); if (persistent && PGG(allow_persistent)) { zend_resource *le; \/* try to find if we already have this link in our persistent list *\/ if ((le = zend_hash_find_ptr(&EG(persistent_list), str.s)) == NULL) { \/* we don't *\/ zend_resource new_le; if (PGG(max_links) != -1 && PGG(num_links) >= PGG(max_links)) { php_error_docref(NULL, E_WARNING, \"Cannot create new link. Too many open links (%pd)\", PGG(num_links)); goto err; } if (PGG(max_persistent) != -1 && PGG(num_persistent) >= PGG(max_persistent)) { php_error_docref(NULL, E_WARNING, \"Cannot create new link. Too many open persistent links (%pd)\", PGG(num_persistent)); goto err; } \/* create the link *\/ if (connstring) { pgsql = PQconnectdb(connstring); } else { pgsql = PQsetdb(host, port, options, tty, dbname); } if (pgsql == NULL || PQstatus(pgsql) == CONNECTION_BAD) { PHP_PQ_ERROR(\"Unable to connect to PostgreSQL server: %s\", pgsql) if (pgsql) { PQfinish(pgsql); } goto err; } \/* hash it up *\/ new_le.type = le_plink; new_le.ptr = pgsql; if (zend_hash_str_update_mem(&EG(persistent_list), str.s->val, str.s->len, &new_le, sizeof(zend_resource)) == NULL) { goto err; } PGG(num_links)++; PGG(num_persistent)++; } else { \/* we do *\/ if (le->type != le_plink) { RETURN_FALSE; } \/* ensure that the link did not die *\/ if (PGG(auto_reset_persistent) & 1) { \/* need to send & get something from backend to make sure we catch CONNECTION_BAD every time *\/ PGresult *pg_result; pg_result = PQexec(le->ptr, \"select 1\"); PQclear(pg_result); } if (PQstatus(le->ptr) == CONNECTION_BAD) { \/* the link died *\/ if (le->ptr == NULL) { if (connstring) { le->ptr = PQconnectdb(connstring); } else { le->ptr = PQsetdb(host,port,options,tty,dbname); } } else { PQreset(le->ptr); } if (le->ptr == NULL || PQstatus(le->ptr) == CONNECTION_BAD) { php_error_docref(NULL, E_WARNING,\"PostgreSQL link lost, unable to reconnect\"); zend_hash_del(&EG(persistent_list), str.s); goto err; } } pgsql = (PGconn *) le->ptr; #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, \"server_version\")) >= 7.2) { #else if (atof(PG_VERSION) >= 7.2) { #endif pg_result = PQexec(pgsql, \"RESET ALL;\"); PQclear(pg_result); } } ZEND_REGISTER_RESOURCE(return_value, pgsql, le_plink); } else { \/* Non persistent connection *\/ zend_resource *index_ptr, new_index_ptr; \/* first we check the hash for the hashed_details key. if it exists, * it should point us to the right offset where the actual pgsql link sits. * if it doesn't, open a new pgsql link, add it to the resource list, * and add a pointer to it with hashed_details as the key. *\/ if (!(connect_type & PGSQL_CONNECT_FORCE_NEW) && (index_ptr = zend_hash_find_ptr(&EG(regular_list), str.s)) != NULL) { zend_resource *link; if (index_ptr->type != le_index_ptr) { RETURN_FALSE; } link = (zend_resource *)index_ptr->ptr; if (link->ptr && (link->type == le_link || link->type == le_plink)) { php_pgsql_set_default_link(link); GC_REFCOUNT(link)++; RETVAL_RES(link); goto cleanup; } else { zend_hash_del(&EG(regular_list), str.s); } } if (PGG(max_links) != -1 && PGG(num_links) >= PGG(max_links)) { php_error_docref(NULL, E_WARNING, \"Cannot create new link. Too many open links (%pd)\", PGG(num_links)); goto err; } \/* Non-blocking connect *\/ if (connect_type & PGSQL_CONNECT_ASYNC) { if (connstring) { pgsql = PQconnectStart(connstring); if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) { PHP_PQ_ERROR(\"Unable to connect to PostgreSQL server: %s\", pgsql); if (pgsql) { PQfinish(pgsql); } goto err; } } else { php_error_docref(NULL, E_WARNING, \"Connection string required for async connections\"); goto err; } } else { if (connstring) { pgsql = PQconnectdb(connstring); } else { pgsql = PQsetdb(host,port,options,tty,dbname); } if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) { PHP_PQ_ERROR(\"Unable to connect to PostgreSQL server: %s\", pgsql); if (pgsql) { PQfinish(pgsql); } goto err; } } \/* add it to the list *\/ ZEND_REGISTER_RESOURCE(return_value, pgsql, le_link); \/* add it to the hash *\/ new_index_ptr.ptr = (void *) Z_RES_P(return_value); new_index_ptr.type = le_index_ptr; if (zend_hash_update_mem(&EG(regular_list), str.s, (void *) &new_index_ptr, sizeof(zend_resource)) == NULL) { goto err; } PGG(num_links)++; } \/* set notice processor *\/ if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) { PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void*)Z_RES_HANDLE_P(return_value)); } php_pgsql_set_default_link(Z_RES_P(return_value)); cleanup: smart_str_free(&str); return; err: smart_str_free(&str); RETURN_FALSE; } \/* }}} *\/ #if 0 \/* {{{ php_pgsql_get_default_link *\/ static int php_pgsql_get_default_link(INTERNAL_FUNCTION_PARAMETERS) { if (PGG(default_link)==-1) { \/* no link opened yet, implicitly open one *\/ ht = 0; php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0); } return PGG(default_link); } \/* }}} *\/ #endif \/* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database) Open a PostgreSQL connection *\/ PHP_FUNCTION(pg_connect) { php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0); } \/* }}} *\/ \/* {{{ proto resource pg_connect_poll(resource connection) Poll the status of an in-progress async PostgreSQL connection attempt*\/ PHP_FUNCTION(pg_connect_poll) { zval *pgsql_link; int id = -1; PGconn *pgsql; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r\", &pgsql_link) == FAILURE) { return; } if (pgsql_link == NULL) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); ret = PQconnectPoll(pgsql); RETURN_LONG(ret); } \/* }}} *\/ \/* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database) Open a persistent PostgreSQL connection *\/ PHP_FUNCTION(pg_pconnect) { php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1); } \/* }}} *\/ \/* {{{ proto bool pg_close([resource connection]) Close a PostgreSQL connection *\/ PHP_FUNCTION(pg_close) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (zend_parse_parameters(argc, \"|r\", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (id==-1) { \/* explicit resource number *\/ zend_list_close(Z_RES_P(pgsql_link)); } if (id!=-1 || (pgsql_link && Z_RES_P(pgsql_link) == PGG(default_link))) { zend_list_close(PGG(default_link)); PGG(default_link) = NULL; } RETURN_TRUE; } \/* }}} *\/ #define PHP_PG_DBNAME 1 #define PHP_PG_ERROR_MESSAGE 2 #define PHP_PG_OPTIONS 3 #define PHP_PG_PORT 4 #define PHP_PG_TTY 5 #define PHP_PG_HOST 6 #define PHP_PG_VERSION 7 \/* {{{ php_pgsql_get_link_info *\/ static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; char *msgbuf; char *result; if (zend_parse_parameters(argc, \"|r\", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); switch(entry_type) { case PHP_PG_DBNAME: result = PQdb(pgsql); break; case PHP_PG_ERROR_MESSAGE: result = PQErrorMessageTrim(pgsql, &msgbuf); RETVAL_STRING(result); efree(result); return; case PHP_PG_OPTIONS: result = PQoptions(pgsql); break; case PHP_PG_PORT: result = PQport(pgsql); break; case PHP_PG_TTY: result = PQtty(pgsql); break; case PHP_PG_HOST: result = PQhost(pgsql); break; case PHP_PG_VERSION: array_init(return_value); add_assoc_string(return_value, \"client\", PG_VERSION); #if HAVE_PQPROTOCOLVERSION add_assoc_long(return_value, \"protocol\", PQprotocolVersion(pgsql)); #if HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3) { \/* 8.0 or grater supports protorol version 3 *\/ char *tmp; add_assoc_string(return_value, \"server\", (char*)PQparameterStatus(pgsql, \"server_version\")); tmp = (char*)PQparameterStatus(pgsql, \"server_encoding\"); add_assoc_string(return_value, \"server_encoding\", tmp); tmp = (char*)PQparameterStatus(pgsql, \"client_encoding\"); add_assoc_string(return_value, \"client_encoding\", tmp); tmp = (char*)PQparameterStatus(pgsql, \"is_superuser\"); add_assoc_string(return_value, \"is_superuser\", tmp); tmp = (char*)PQparameterStatus(pgsql, \"session_authorization\"); add_assoc_string(return_value, \"session_authorization\", tmp); tmp = (char*)PQparameterStatus(pgsql, \"DateStyle\"); add_assoc_string(return_value, \"DateStyle\", tmp); tmp = (char*)PQparameterStatus(pgsql, \"IntervalStyle\"); add_assoc_string(return_value, \"IntervalStyle\", tmp ? tmp : \"\"); tmp = (char*)PQparameterStatus(pgsql, \"TimeZone\"); add_assoc_string(return_value, \"TimeZone\", tmp ? tmp : \"\"); tmp = (char*)PQparameterStatus(pgsql, \"integer_datetimes\"); add_assoc_string(return_value, \"integer_datetimes\", tmp ? tmp : \"\"); tmp = (char*)PQparameterStatus(pgsql, \"standard_conforming_strings\"); add_assoc_string(return_value, \"standard_conforming_strings\", tmp ? tmp : \"\"); tmp = (char*)PQparameterStatus(pgsql, \"application_name\"); add_assoc_string(return_value, \"application_name\", tmp ? tmp : \"\"); } #endif #endif return; default: RETURN_FALSE; } if (result) { RETURN_STRING(result); } else { RETURN_EMPTY_STRING(); } } \/* }}} *\/ \/* {{{ proto string pg_dbname([resource connection]) Get the database name *\/ PHP_FUNCTION(pg_dbname) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME); } \/* }}} *\/ \/* {{{ proto string pg_last_error([resource connection]) Get the error message string *\/ PHP_FUNCTION(pg_last_error) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE); } \/* }}} *\/ \/* {{{ proto string pg_options([resource connection]) Get the options associated with the connection *\/ PHP_FUNCTION(pg_options) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS); } \/* }}} *\/ \/* {{{ proto int pg_port([resource connection]) Return the port number associated with the connection *\/ PHP_FUNCTION(pg_port) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT); } \/* }}} *\/ \/* {{{ proto string pg_tty([resource connection]) Return the tty name associated with the connection *\/ PHP_FUNCTION(pg_tty) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY); } \/* }}} *\/ \/* {{{ proto string pg_host([resource connection]) Returns the host name associated with the connection *\/ PHP_FUNCTION(pg_host) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST); } \/* }}} *\/ \/* {{{ proto array pg_version([resource connection]) Returns an array with client, protocol and server version (when available) *\/ PHP_FUNCTION(pg_version) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION); } \/* }}} *\/ #if HAVE_PQPARAMETERSTATUS \/* {{{ proto string|false pg_parameter_status([resource connection,] string param_name) Returns the value of a server parameter *\/ PHP_FUNCTION(pg_parameter_status) { zval *pgsql_link; int id; PGconn *pgsql; char *param; size_t len; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"rs\", &pgsql_link, ¶m, &len) == SUCCESS) { id = -1; } else if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", ¶m, &len) == SUCCESS) { pgsql_link = NULL; id = FETCH_DEFAULT_LINK(); } else { RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); param = (char*)PQparameterStatus(pgsql, param); if (param) { RETURN_STRING(param); } else { RETURN_FALSE; } } \/* }}} *\/ #endif \/* {{{ proto bool pg_ping([resource connection]) Ping database. If connection is bad, try to reconnect. *\/ PHP_FUNCTION(pg_ping) { zval *pgsql_link; int id; PGconn *pgsql; PGresult *res; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"r\", &pgsql_link) == SUCCESS) { id = -1; } else { pgsql_link = NULL; id = FETCH_DEFAULT_LINK(); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); \/* ping connection *\/ res = PQexec(pgsql, \"SELECT 1;\"); PQclear(res); \/* check status. *\/ if (PQstatus(pgsql) == CONNECTION_OK) RETURN_TRUE; \/* reset connection if it's broken *\/ PQreset(pgsql); if (PQstatus(pgsql) == CONNECTION_OK) { RETURN_TRUE; } RETURN_FALSE; } \/* }}} *\/ \/* {{{ proto resource pg_query([resource connection,] string query) Execute a query *\/ PHP_FUNCTION(pg_query) { zval *pgsql_link = NULL; char *query; int id = -1, argc = ZEND_NUM_ARGS(); size_t query_len; int leftover = 0; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &query, &query_len) == FAILURE) { return; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rs\", &pgsql_link, &query, &query_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE,\"Cannot set connection to blocking mode\"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL, E_NOTICE, \"Found results on this connection. Use pg_get_result() to get these results first\"); } pgsql_result = PQexec(pgsql, query); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexec(pgsql, query); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR(\"Query failed: %s\", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: \/* successful command that did not return rows *\/ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } \/* }}} *\/ #if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED \/* {{{ _php_pgsql_free_params *\/ static void _php_pgsql_free_params(char **params, int num_params) { if (num_params > 0) { int i; for (i = 0; i < num_params; i++) { if (params[i]) { efree(params[i]); } } efree(params); } } \/* }}} *\/ #endif #if HAVE_PQEXECPARAMS \/* {{{ proto resource pg_query_params([resource connection,] string query, array params) Execute a query *\/ PHP_FUNCTION(pg_query_params) { zval *pgsql_link = NULL; zval *pv_param_arr, *tmp; char *query; size_t query_len; int id = -1, argc = ZEND_NUM_ARGS(); int leftover = 0; int num_params = 0; char **params = NULL; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc, \"sa\", &query, &query_len, &pv_param_arr) == FAILURE) { return; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc, \"rsa\", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE,\"Cannot set connection to blocking mode\"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL, E_NOTICE, \"Found results on this connection. Use pg_get_result() to get these results first\"); } num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) { if (Z_TYPE_P(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val; ZVAL_COPY(&tmp_val, tmp); convert_to_cstring(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL, E_WARNING,\"Error converting parameter\"); zval_ptr_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_ptr_dtor(&tmp_val); } i++; } ZEND_HASH_FOREACH_END(); } pgsql_result = PQexecParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexecParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } _php_pgsql_free_params(params, num_params); switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR(\"Query failed: %s\", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: \/* successful command that did not return rows *\/ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } \/* }}} *\/ #endif #if HAVE_PQPREPARE \/* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query) Prepare a query for future execution *\/ PHP_FUNCTION(pg_prepare) { zval *pgsql_link = NULL; char *query, *stmtname; size_t query_len, stmtname_len; int id = -1, argc = ZEND_NUM_ARGS(); int leftover = 0; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc, \"ss\", &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc, \"rss\", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE,\"Cannot set connection to blocking mode\"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL, E_NOTICE, \"Found results on this connection. Use pg_get_result() to get these results first\"); } pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR(\"Query failed: %s\", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: \/* successful command that did not return rows *\/ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } \/* }}} *\/ #endif #if HAVE_PQEXECPREPARED \/* {{{ proto resource pg_execute([resource connection,] string stmtname, array params) Execute a prepared query *\/ PHP_FUNCTION(pg_execute) { zval *pgsql_link = NULL; zval *pv_param_arr, *tmp; char *stmtname; size_t stmtname_len; int id = -1, argc = ZEND_NUM_ARGS(); int leftover = 0; int num_params = 0; char **params = NULL; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc, \"sa\/\", &stmtname, &stmtname_len, &pv_param_arr)==FAILURE) { return; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc, \"rsa\/\", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE,\"Cannot set connection to blocking mode\"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL, E_NOTICE, \"Found results on this connection. Use pg_get_result() to get these results first\"); } num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) { if (Z_TYPE_P(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val; ZVAL_COPY(&tmp_val, tmp); convert_to_string(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL, E_WARNING,\"Error converting parameter\"); zval_ptr_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_ptr_dtor(&tmp_val); } i++; } ZEND_HASH_FOREACH_END(); } pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } _php_pgsql_free_params(params, num_params); switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR(\"Query failed: %s\", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: \/* successful command that did not return rows *\/ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } \/* }}} *\/ #endif #define PHP_PG_NUM_ROWS 1 #define PHP_PG_NUM_FIELDS 2 #define PHP_PG_CMD_TUPLES 3 \/* {{{ php_pgsql_get_result_info *\/ static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r\", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; switch (entry_type) { case PHP_PG_NUM_ROWS: RETVAL_LONG(PQntuples(pgsql_result)); break; case PHP_PG_NUM_FIELDS: RETVAL_LONG(PQnfields(pgsql_result)); break; case PHP_PG_CMD_TUPLES: #if HAVE_PQCMDTUPLES RETVAL_LONG(atoi(PQcmdTuples(pgsql_result))); #else php_error_docref(NULL, E_WARNING, \"Not supported under this build\"); RETVAL_LONG(0); #endif break; default: RETURN_FALSE; } } \/* }}} *\/ \/* {{{ proto int pg_num_rows(resource result) Return the number of rows in the result *\/ PHP_FUNCTION(pg_num_rows) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS); } \/* }}} *\/ \/* {{{ proto int pg_num_fields(resource result) Return the number of fields in the result *\/ PHP_FUNCTION(pg_num_fields) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS); } \/* }}} *\/ #if HAVE_PQCMDTUPLES \/* {{{ proto int pg_affected_rows(resource result) Returns the number of affected tuples *\/ PHP_FUNCTION(pg_affected_rows) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES); } \/* }}} *\/ #endif \/* {{{ proto string pg_last_notice(resource connection) Returns the last notice set by the backend *\/ PHP_FUNCTION(pg_last_notice) { zval *pgsql_link = NULL; PGconn *pg_link; int id = -1; php_pgsql_notice *notice; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r\", &pgsql_link) == FAILURE) { return; } if (pgsql_link == NULL) { RETURN_FALSE; } \/* Just to check if user passed valid resoruce *\/ ZEND_FETCH_RESOURCE2(pg_link, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if ((notice = zend_hash_index_find_ptr(&PGG(notices), (zend_ulong)Z_RES_HANDLE_P(pgsql_link))) == NULL) { RETURN_FALSE; } RETURN_STRINGL(notice->message, notice->len); } \/* }}} *\/ \/* {{{ get_field_name *\/ static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list) { PGresult *result; smart_str str = {0}; zend_resource *field_type; char *ret=NULL; \/* try to lookup the type in the resource list *\/ smart_str_appends(&str, \"pgsql_oid_\"); smart_str_append_unsigned(&str, oid); smart_str_0(&str); if ((field_type = zend_hash_find_ptr(list, str.s)) != NULL) { ret = estrdup((char *)field_type->ptr); } else { \/* hash all oid's *\/ int i, num_rows; int oid_offset,name_offset; char *tmp_oid, *end_ptr, *tmp_name; zend_resource new_oid_entry; if ((result = PQexec(pgsql, \"select oid,typname from pg_type\")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) { if (result) { PQclear(result); } smart_str_free(&str); return estrndup(\"\", sizeof(\"\") - 1); } num_rows = PQntuples(result); oid_offset = PQfnumber(result,\"oid\"); name_offset = PQfnumber(result,\"typname\"); for (i=0; ilen = 0; smart_str_appends(&str, \"pgsql_oid_\"); smart_str_appends(&str, tmp_oid); smart_str_0(&str); if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) { continue; } new_oid_entry.type = le_string; new_oid_entry.ptr = estrdup(tmp_name); zend_hash_update_mem(list, str.s, (void *) &new_oid_entry, sizeof(zend_resource)); if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) { ret = estrdup(tmp_name); } } PQclear(result); } smart_str_free(&str); return ret; } \/* }}} *\/ #ifdef HAVE_PQFTABLE \/* {{{ proto mixed pg_field_table(resource result, int field_number[, bool oid_only]) Returns the name of the table field belongs to, or table's oid if oid_only is true *\/ PHP_FUNCTION(pg_field_table) { zval *result; pgsql_result_handle *pg_result; zend_long fnum = -1; zend_bool return_oid = 0; Oid oid; smart_str hash_key = {0}; char *table_name; zend_resource *field_table; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rl|b\", &result, &fnum, &return_oid) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); if (fnum < 0 || fnum >= PQnfields(pg_result->result)) { php_error_docref(NULL, E_WARNING, \"Bad field offset specified\"); RETURN_FALSE; } oid = PQftable(pg_result->result, (int)fnum); if (InvalidOid == oid) { RETURN_FALSE; } if (return_oid) { #if UINT_MAX > ZEND_LONG_MAX \/* Oid is unsigned int, we don't need this code, where LONG is wider *\/ if (oid > ZEND_LONG_MAX) { smart_str oidstr = {0}; smart_str_append_unsigned(&oidstr, oid); smart_str_0(&oidstr); RETURN_STR(oidstr.s); } else #endif RETURN_LONG((zend_long)oid); } \/* try to lookup the table name in the resource list *\/ smart_str_appends(&hash_key, \"pgsql_table_oid_\"); smart_str_append_unsigned(&hash_key, oid); smart_str_0(&hash_key); if ((field_table = zend_hash_find_ptr(&EG(regular_list), hash_key.s)) != NULL) { smart_str_free(&hash_key); RETURN_STRING((char *)field_table->ptr); } else { \/* Not found, lookup by querying PostgreSQL system tables *\/ PGresult *tmp_res; smart_str querystr = {0}; zend_resource new_field_table; smart_str_appends(&querystr, \"select relname from pg_class where oid=\"); smart_str_append_unsigned(&querystr, oid); smart_str_0(&querystr); if ((tmp_res = PQexec(pg_result->conn, querystr.s->val)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) { if (tmp_res) { PQclear(tmp_res); } smart_str_free(&querystr); smart_str_free(&hash_key); RETURN_FALSE; } smart_str_free(&querystr); if ((table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) { PQclear(tmp_res); smart_str_free(&hash_key); RETURN_FALSE; } new_field_table.type = le_string; new_field_table.ptr = estrdup(table_name); zend_hash_update_mem(&EG(regular_list), hash_key.s, (void *)&new_field_table, sizeof(zend_resource)); smart_str_free(&hash_key); PQclear(tmp_res); RETURN_STRING(table_name); } } \/* }}} *\/ #endif #define PHP_PG_FIELD_NAME 1 #define PHP_PG_FIELD_SIZE 2 #define PHP_PG_FIELD_TYPE 3 #define PHP_PG_FIELD_TYPE_OID 4 \/* {{{ php_pgsql_get_field_info *\/ static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result; zend_long field; PGresult *pgsql_result; pgsql_result_handle *pg_result; Oid oid; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rl\", &result, &field) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; if (field < 0 || field >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, \"Bad field offset specified\"); RETURN_FALSE; } switch (entry_type) { case PHP_PG_FIELD_NAME: RETURN_STRING(PQfname(pgsql_result, (int)field)); break; case PHP_PG_FIELD_SIZE: RETURN_LONG(PQfsize(pgsql_result, (int)field)); break; case PHP_PG_FIELD_TYPE: { char *name = get_field_name(pg_result->conn, PQftype(pgsql_result, (int)field), &EG(regular_list)); RETVAL_STRING(name); efree(name); } break; case PHP_PG_FIELD_TYPE_OID: oid = PQftype(pgsql_result, (int)field); #if UINT_MAX > ZEND_LONG_MAX if (oid > ZEND_LONG_MAX) { smart_str s = {0}; smart_str_append_unsigned(&s, oid); smart_str_0(&s); RETURN_STR(s.s); } else #endif { RETURN_LONG((zend_long)oid); } break; default: RETURN_FALSE; } } \/* }}} *\/ \/* {{{ proto string pg_field_name(resource result, int field_number) Returns the name of the field *\/ PHP_FUNCTION(pg_field_name) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME); } \/* }}} *\/ \/* {{{ proto int pg_field_size(resource result, int field_number) Returns the internal size of the field *\/ PHP_FUNCTION(pg_field_size) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE); } \/* }}} *\/ \/* {{{ proto string pg_field_type(resource result, int field_number) Returns the type name for the given field *\/ PHP_FUNCTION(pg_field_type) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE); } \/* }}} *\/ \/* {{{ proto string pg_field_type_oid(resource result, int field_number) Returns the type oid for the given field *\/ PHP_FUNCTION(pg_field_type_oid) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID); } \/* }}} *\/ \/* {{{ proto int pg_field_num(resource result, string field_name) Returns the field number of the named field *\/ PHP_FUNCTION(pg_field_num) { zval *result; char *field; size_t field_len; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rs\", &result, &field, &field_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; RETURN_LONG(PQfnumber(pgsql_result, field)); } \/* }}} *\/ \/* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name) Returns values from a result identifier *\/ PHP_FUNCTION(pg_fetch_result) { zval *result, *field=NULL; zend_long row; PGresult *pgsql_result; pgsql_result_handle *pg_result; int field_offset, pgsql_row, argc = ZEND_NUM_ARGS(); if (argc == 2) { if (zend_parse_parameters(argc, \"rz\", &result, &field) == FAILURE) { return; } } else { if (zend_parse_parameters(argc, \"rlz\", &result, &row, &field) == FAILURE) { return; } } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; if (argc == 2) { if (pg_result->row < 0) { pg_result->row = 0; } pgsql_row = pg_result->row; if (pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } } else { if (row < 0 || row >= PQntuples(pgsql_result)) { php_error_docref(NULL, E_WARNING, \"Unable to jump to row %pd on PostgreSQL result index %pd\", row, Z_LVAL_P(result)); RETURN_FALSE; } pgsql_row = (int)row; } switch (Z_TYPE_P(field)) { case IS_STRING: field_offset = PQfnumber(pgsql_result, Z_STRVAL_P(field)); if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, \"Bad column offset specified\"); RETURN_FALSE; } break; default: convert_to_long_ex(field); if (Z_LVAL_P(field) < 0 || Z_LVAL_P(field) >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, \"Bad column offset specified\"); RETURN_FALSE; } field_offset = (int)Z_LVAL_P(field); break; } if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) { RETVAL_NULL(); } else { RETVAL_STRINGL(PQgetvalue(pgsql_result, pgsql_row, field_offset), PQgetlength(pgsql_result, pgsql_row, field_offset)); } } \/* }}} *\/ \/* {{{ void php_pgsql_fetch_hash *\/ static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, zend_long result_type, int into_object) { zval *result, *zrow = NULL; PGresult *pgsql_result; pgsql_result_handle *pg_result; int i, num_fields, pgsql_row, use_row; zend_long row = -1; char *field_name; zval *ctor_params = NULL; zend_class_entry *ce = NULL; if (into_object) { zend_string *class_name = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r|z!Sz\", &result, &zrow, &class_name, &ctor_params) == FAILURE) { return; } if (!class_name) { ce = zend_standard_class_def; } else { ce = zend_fetch_class(class_name, ZEND_FETCH_CLASS_AUTO); } if (!ce) { php_error_docref(NULL, E_WARNING, \"Could not find class '%s'\", class_name->val); return; } result_type = PGSQL_ASSOC; } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r|z!l\", &result, &zrow, &result_type) == FAILURE) { return; } } if (zrow == NULL) { row = -1; } else { convert_to_long(zrow); row = Z_LVAL_P(zrow); if (row < 0) { php_error_docref(NULL, E_WARNING, \"The row parameter must be greater or equal to zero\"); RETURN_FALSE; } } use_row = ZEND_NUM_ARGS() > 1 && row != -1; if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL, E_WARNING, \"Invalid result type\"); RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; if (use_row) { if (row < 0 || row >= PQntuples(pgsql_result)) { php_error_docref(NULL, E_WARNING, \"Unable to jump to row %pd on PostgreSQL result index %pd\", row, Z_LVAL_P(result)); RETURN_FALSE; } pgsql_row = (int)row; pg_result->row = pgsql_row; } else { \/* If 2nd param is NULL, use internal row counter to access next row *\/ pgsql_row = pg_result->row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } pg_result->row++; } array_init(return_value); for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) { if (PQgetisnull(pgsql_result, pgsql_row, i)) { if (result_type & PGSQL_NUM) { add_index_null(return_value, i); } if (result_type & PGSQL_ASSOC) { field_name = PQfname(pgsql_result, i); add_assoc_null(return_value, field_name); } } else { char *element = PQgetvalue(pgsql_result, pgsql_row, i); if (element) { const size_t element_len = strlen(element); if (result_type & PGSQL_NUM) { add_index_stringl(return_value, i, element, element_len); } if (result_type & PGSQL_ASSOC) { field_name = PQfname(pgsql_result, i); add_assoc_stringl(return_value, field_name, element, element_len); } } } } if (into_object) { zval dataset; zend_fcall_info fci; zend_fcall_info_cache fcc; zval retval; ZVAL_COPY_VALUE(&dataset, return_value); object_and_properties_init(return_value, ce, NULL); if (!ce->default_properties_count && !ce->__set) { ALLOC_HASHTABLE(Z_OBJ_P(return_value)->properties); *Z_OBJ_P(return_value)->properties = *Z_ARRVAL(dataset); efree(Z_ARR(dataset)); } else { zend_merge_properties(return_value, Z_ARRVAL(dataset)); zval_ptr_dtor(&dataset); } if (ce->constructor) { fci.size = sizeof(fci); fci.function_table = &ce->function_table; ZVAL_UNDEF(&fci.function_name); fci.symbol_table = NULL; fci.object = Z_OBJ_P(return_value); fci.retval = &retval; fci.params = NULL; fci.param_count = 0; fci.no_separation = 1; if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) { if (zend_fcall_info_args(&fci, ctor_params) == FAILURE) { \/* Two problems why we throw exceptions here: PHP is typeless * and hence passing one argument that's not an array could be * by mistake and the other way round is possible, too. The * single value is an array. Also we'd have to make that one * argument passed by reference. *\/ zend_throw_exception(zend_exception_get_default(), \"Parameter ctor_params must be an array\", 0); return; } } fcc.initialized = 1; fcc.function_handler = ce->constructor; fcc.calling_scope = EG(scope); fcc.called_scope = Z_OBJCE_P(return_value); fcc.object = Z_OBJ_P(return_value); if (zend_call_function(&fci, &fcc) == FAILURE) { zend_throw_exception_ex(zend_exception_get_default(), 0, \"Could not execute %s::%s()\", ce->name, ce->constructor->common.function_name); } else { zval_ptr_dtor(&retval); } if (fci.params) { efree(fci.params); } } else if (ctor_params) { zend_throw_exception_ex(zend_exception_get_default(), 0, \"Class %s does not have a constructor hence you cannot use ctor_params\", ce->name); } } } \/* }}} *\/ \/* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]]) Get a row as an enumerated array *\/ PHP_FUNCTION(pg_fetch_row) { php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0); } \/* }}} *\/ \/* {{{ proto array pg_fetch_assoc(resource result [, int row]) Fetch a row as an assoc array *\/ PHP_FUNCTION(pg_fetch_assoc) { \/* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when there is 3rd parameter *\/ if (ZEND_NUM_ARGS() > 2) WRONG_PARAM_COUNT; php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0); } \/* }}} *\/ \/* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]]) Fetch a row as an array *\/ PHP_FUNCTION(pg_fetch_array) { php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0); } \/* }}} *\/ \/* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]]) Fetch a row as an object *\/ PHP_FUNCTION(pg_fetch_object) { \/* pg_fetch_object() allowed result_type used to be. 3rd parameter must be allowed for compatibility *\/ php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1); } \/* }}} *\/ \/* {{{ proto array pg_fetch_all(resource result) Fetch all rows into array *\/ PHP_FUNCTION(pg_fetch_all) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r\", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; array_init(return_value); if (php_pgsql_result2array(pgsql_result, return_value) == FAILURE) { zval_dtor(return_value); RETURN_FALSE; } } \/* }}} *\/ \/* {{{ proto array pg_fetch_all_columns(resource result [, int column_number]) Fetch all rows into array *\/ PHP_FUNCTION(pg_fetch_all_columns) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; zend_long colno=0; int pg_numrows, pg_row; size_t num_fields; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r|l\", &result, &colno) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; num_fields = PQnfields(pgsql_result); if (colno >= (zend_long)num_fields || colno < 0) { php_error_docref(NULL, E_WARNING, \"Invalid column number '%pd'\", colno); RETURN_FALSE; } array_init(return_value); if ((pg_numrows = PQntuples(pgsql_result)) <= 0) { return; } for (pg_row = 0; pg_row < pg_numrows; pg_row++) { if (PQgetisnull(pgsql_result, pg_row, (int)colno)) { add_next_index_null(return_value); } else { add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, (int)colno)); } } } \/* }}} *\/ \/* {{{ proto bool pg_result_seek(resource result, int offset) Set internal row offset *\/ PHP_FUNCTION(pg_result_seek) { zval *result; zend_long row; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rl\", &result, &row) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); if (row < 0 || row >= PQntuples(pg_result->result)) { RETURN_FALSE; } \/* seek to offset *\/ pg_result->row = (int)row; RETURN_TRUE; } \/* }}} *\/ #define PHP_PG_DATA_LENGTH 1 #define PHP_PG_DATA_ISNULL 2 \/* {{{ php_pgsql_data_info *\/ static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result, *field; zend_long row; PGresult *pgsql_result; pgsql_result_handle *pg_result; int field_offset, pgsql_row, argc = ZEND_NUM_ARGS(); if (argc == 2) { if (zend_parse_parameters(argc, \"rz\", &result, &field) == FAILURE) { return; } } else { if (zend_parse_parameters(argc, \"rlz\", &result, &row, &field) == FAILURE) { return; } } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; if (argc == 2) { if (pg_result->row < 0) { pg_result->row = 0; } pgsql_row = pg_result->row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } } else { if (row < 0 || row >= PQntuples(pgsql_result)) { php_error_docref(NULL, E_WARNING, \"Unable to jump to row %pd on PostgreSQL result index %pd\", row, Z_LVAL_P(result)); RETURN_FALSE; } pgsql_row = (int)row; } switch (Z_TYPE_P(field)) { case IS_STRING: convert_to_string_ex(field); field_offset = PQfnumber(pgsql_result, Z_STRVAL_P(field)); if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, \"Bad column offset specified\"); RETURN_FALSE; } break; default: convert_to_long_ex(field); if (Z_LVAL_P(field) < 0 || Z_LVAL_P(field) >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, \"Bad column offset specified\"); RETURN_FALSE; } field_offset = (int)Z_LVAL_P(field); break; } switch (entry_type) { case PHP_PG_DATA_LENGTH: RETVAL_LONG(PQgetlength(pgsql_result, pgsql_row, field_offset)); break; case PHP_PG_DATA_ISNULL: RETVAL_LONG(PQgetisnull(pgsql_result, pgsql_row, field_offset)) break; } } \/* }}} *\/ \/* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number) Returns the printed length *\/ PHP_FUNCTION(pg_field_prtlen) { php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH); } \/* }}} *\/ \/* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number) Test if a field is NULL *\/ PHP_FUNCTION(pg_field_is_null) { php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL); } \/* }}} *\/ \/* {{{ proto bool pg_free_result(resource result) Free result memory *\/ PHP_FUNCTION(pg_free_result) { zval *result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r\", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); if (Z_RES_P(result) == NULL) { RETURN_FALSE; } zend_list_close(Z_RES_P(result)); RETURN_TRUE; } \/* }}} *\/ \/* {{{ proto string pg_last_oid(resource result) Returns the last object identifier *\/ PHP_FUNCTION(pg_last_oid) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; #ifdef HAVE_PQOIDVALUE Oid oid; #endif if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r\", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; #ifdef HAVE_PQOIDVALUE oid = PQoidValue(pgsql_result); if (oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(oid); #else Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result); if (Z_STRVAL_P(return_value)) { RETURN_STRING(Z_STRVAL_P(return_value)); } RETURN_EMPTY_STRING(); #endif } \/* }}} *\/ \/* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]]) Enable tracing a PostgreSQL connection *\/ PHP_FUNCTION(pg_trace) { char *z_filename, *mode = \"w\"; size_t z_filename_len, mode_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; FILE *fp = NULL; php_stream *stream; id = FETCH_DEFAULT_LINK(); if (zend_parse_parameters(argc, \"s|sr\", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) { return; } if (argc < 3) { CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL); if (!stream) { RETURN_FALSE; } if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { php_stream_close(stream); RETURN_FALSE; } php_stream_auto_cleanup(stream); PQtrace(pgsql, fp); RETURN_TRUE; } \/* }}} *\/ \/* {{{ proto bool pg_untrace([resource connection]) Disable tracing of a PostgreSQL connection *\/ PHP_FUNCTION(pg_untrace) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (zend_parse_parameters(argc, \"|r\", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); PQuntrace(pgsql); RETURN_TRUE; } \/* }}} *\/ \/* {{{ proto mixed pg_lo_create([resource connection],[mixed large_object_oid]) Create a large object *\/ PHP_FUNCTION(pg_lo_create) { zval *pgsql_link = NULL, *oid = NULL; PGconn *pgsql; Oid pgsql_oid, wanted_oid = InvalidOid; int id = -1, argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, \"|zz\", &pgsql_link, &oid) == FAILURE) { return; } if ((argc == 1) && (Z_TYPE_P(pgsql_link) != IS_RESOURCE)) { oid = pgsql_link; pgsql_link = NULL; } if (pgsql_link == NULL) { id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); if (id == -1) { RETURN_FALSE; } } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (oid) { #ifndef HAVE_PG_LO_CREATE php_error_docref(NULL, E_NOTICE, \"Passing OID value is not supported. Upgrade your PostgreSQL\"); #else switch (Z_TYPE_P(oid)) { case IS_STRING: { char *end_ptr; wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10); if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) { \/* wrong integer format *\/ php_error_docref(NULL, E_NOTICE, \"invalid OID value passed\"); RETURN_FALSE; } } break; case IS_LONG: if (Z_LVAL_P(oid) < (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, \"invalid OID value passed\"); RETURN_FALSE; } wanted_oid = (Oid)Z_LVAL_P(oid); break; default: php_error_docref(NULL, E_NOTICE, \"invalid OID value passed\"); RETURN_FALSE; } if ((pgsql_oid = lo_create(pgsql, wanted_oid)) == InvalidOid) { php_error_docref(NULL, E_WARNING, \"Unable to create PostgreSQL large object\"); RETURN_FALSE; } PGSQL_RETURN_OID(pgsql_oid); #endif } if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) { php_error_docref(NULL, E_WARNING, \"Unable to create PostgreSQL large object\"); RETURN_FALSE; } PGSQL_RETURN_OID(pgsql_oid); } \/* }}} *\/ \/* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid) Delete a large object *\/ PHP_FUNCTION(pg_lo_unlink) { zval *pgsql_link = NULL; zend_long oid_long; char *oid_string, *end_ptr; size_t oid_strlen; PGconn *pgsql; Oid oid; int id = -1; int argc = ZEND_NUM_ARGS(); \/* accept string type since Oid type is unsigned int *\/ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"rs\", &pgsql_link, &oid_string, &oid_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { \/* wrong integer format *\/ php_error_docref(NULL, E_NOTICE, \"Wrong OID value passed\"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"rl\", &pgsql_link, &oid_long) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL, E_NOTICE, \"Invalid OID specified\"); RETURN_FALSE; } oid = (Oid)oid_long; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"s\", &oid_string, &oid_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { \/* wrong integer format *\/ php_error_docref(NULL, E_NOTICE, \"Wrong OID value passed\"); RETURN_FALSE; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"l\", &oid_long) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL, E_NOTICE, \"Invalid OID is specified\"); RETURN_FALSE; } oid = (Oid)oid_long; id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else { php_error_docref(NULL, E_WARNING, \"Requires 1 or 2 arguments\"); RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (lo_unlink(pgsql, oid) == -1) { php_error_docref(NULL, E_WARNING, \"Unable to delete PostgreSQL large object %u\", oid); RETURN_FALSE; } RETURN_TRUE; } \/* }}} *\/ \/* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode) Open a large object and return fd *\/ PHP_FUNCTION(pg_lo_open) { zval *pgsql_link = NULL; zend_long oid_long; char *oid_string, *end_ptr, *mode_string; size_t oid_strlen, mode_strlen; PGconn *pgsql; Oid oid; int id = -1, pgsql_mode=0, pgsql_lofd; int create = 0; pgLofp *pgsql_lofp; int argc = ZEND_NUM_ARGS(); \/* accept string type since Oid is unsigned int *\/ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"rss\", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { \/* wrong integer format *\/ php_error_docref(NULL, E_NOTICE, \"Wrong OID value passed\"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"rls\", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL, E_NOTICE, \"Invalid OID specified\"); RETURN_FALSE; } oid = (Oid)oid_long; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"ss\", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { \/* wrong integer format *\/ php_error_docref(NULL, E_NOTICE, \"Wrong OID value passed\"); RETURN_FALSE; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"ls\", &oid_long, &mode_string, &mode_strlen) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL, E_NOTICE, \"Invalid OID specified\"); RETURN_FALSE; } oid = (Oid)oid_long; id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else { php_error_docref(NULL, E_WARNING, \"Requires 1 or 2 arguments\"); RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); \/* r\/w\/+ is little bit more PHP-like than INV_READ\/INV_WRITE and a lot of faster to type. Unfortunately, doesn't behave the same way as fopen()... (Jouni) *\/ if (strchr(mode_string, 'r') == mode_string) { pgsql_mode |= INV_READ; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_WRITE; } } if (strchr(mode_string, 'w') == mode_string) { pgsql_mode |= INV_WRITE; create = 1; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_READ; } } pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp)); if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (create) { if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) { efree(pgsql_lofp); php_error_docref(NULL, E_WARNING, \"Unable to create PostgreSQL large object\"); RETURN_FALSE; } else { if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (lo_unlink(pgsql, oid) == -1) { efree(pgsql_lofp); php_error_docref(NULL, E_WARNING, \"Something is really messed up! Your database is badly corrupted in a way NOT related to PHP\"); RETURN_FALSE; } efree(pgsql_lofp); php_error_docref(NULL, E_WARNING, \"Unable to open PostgreSQL large object\"); RETURN_FALSE; } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp); } } } else { efree(pgsql_lofp); php_error_docref(NULL, E_WARNING, \"Unable to open PostgreSQL large object\"); RETURN_FALSE; } } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp); } } \/* }}} *\/ \/* {{{ proto bool pg_lo_close(resource large_object) Close a large object *\/ PHP_FUNCTION(pg_lo_close) { zval *pgsql_lofp; pgLofp *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r\", &pgsql_lofp) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_lofp, -1, \"PostgreSQL large object\", le_lofp); if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) { php_error_docref(NULL, E_WARNING, \"Unable to close PostgreSQL large object descriptor %d\", pgsql->lofd); RETVAL_FALSE; } else { RETVAL_TRUE; } zend_list_close(Z_RES_P(pgsql_lofp)); return; } \/* }}} *\/ #define PGSQL_LO_READ_BUF_SIZE 8192 \/* {{{ proto string pg_lo_read(resource large_object [, int len]) Read a large object *\/ PHP_FUNCTION(pg_lo_read) { zval *pgsql_id; zend_long len; size_t buf_len = PGSQL_LO_READ_BUF_SIZE; int nbytes, argc = ZEND_NUM_ARGS(); zend_string *buf; pgLofp *pgsql; if (zend_parse_parameters(argc, \"r|l\", &pgsql_id, &len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, \"PostgreSQL large object\", le_lofp); if (argc > 1) { buf_len = len < 0 ? 0 : len; } buf = zend_string_alloc(buf_len, 0); if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf->val, buf->len))<0) { zend_string_free(buf); RETURN_FALSE; } buf->len = nbytes; buf->val[buf->len] = '\\0'; RETURN_STR(buf); } \/* }}} *\/ \/* {{{ proto int pg_lo_write(resource large_object, string buf [, int len]) Write a large object *\/ PHP_FUNCTION(pg_lo_write) { zval *pgsql_id; char *str; zend_long z_len; size_t str_len, nbytes; size_t len; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, \"rs|l\", &pgsql_id, &str, &str_len, &z_len) == FAILURE) { return; } if (argc > 2) { if (z_len > (zend_long)str_len) { php_error_docref(NULL, E_WARNING, \"Cannot write more than buffer size %d. Tried to write %pd\", str_len, z_len); RETURN_FALSE; } if (z_len < 0) { php_error_docref(NULL, E_WARNING, \"Buffer size must be larger than 0, but %pd was specified\", z_len); RETURN_FALSE; } len = z_len; } else { len = str_len; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, \"PostgreSQL large object\", le_lofp); if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, str, len)) == -1) { RETURN_FALSE; } RETURN_LONG(nbytes); } \/* }}} *\/ \/* {{{ proto int pg_lo_read_all(resource large_object) Read a large object and send straight to browser *\/ PHP_FUNCTION(pg_lo_read_all) { zval *pgsql_id; int tbytes; volatile int nbytes; char buf[PGSQL_LO_READ_BUF_SIZE]; pgLofp *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"r\", &pgsql_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, \"PostgreSQL large object\", le_lofp); tbytes = 0; while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) { PHPWRITE(buf, nbytes); tbytes += nbytes; } RETURN_LONG(tbytes); } \/* }}} *\/ \/* {{{ proto int pg_lo_import([resource connection, ] string filename [, mixed oid]) Import large object direct from filesystem *\/ PHP_FUNCTION(pg_lo_import) { zval *pgsql_link = NULL, *oid = NULL; char *file_in; int id = -1; size_t name_len; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; Oid returned_oid; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"rp|z\", &pgsql_link, &file_in, &name_len, &oid) == SUCCESS) { ; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"p|z\", &file_in, &name_len, &oid) == SUCCESS) { id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } \/* old calling convention, deprecated since PHP 4.2 *\/ else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"pr\", &file_in, &name_len, &pgsql_link ) == SUCCESS) { php_error_docref(NULL, E_NOTICE, \"Old API is used\"); } else { WRONG_PARAM_COUNT; } if (php_check_open_basedir(file_in)) { RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (oid) { #ifndef HAVE_PG_LO_IMPORT_WITH_OID php_error_docref(NULL, E_NOTICE, \"OID value passing not supported\"); #else Oid wanted_oid; switch (Z_TYPE_P(oid)) { case IS_STRING: { char *end_ptr; wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10); if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) { \/* wrong integer format *\/ php_error_docref(NULL, E_NOTICE, \"invalid OID value passed\"); RETURN_FALSE; } } break; case IS_LONG: if (Z_LVAL_P(oid) < (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, \"invalid OID value passed\"); RETURN_FALSE; } wanted_oid = (Oid)Z_LVAL_P(oid); break; default: php_error_docref(NULL, E_NOTICE, \"invalid OID value passed\"); RETURN_FALSE; } returned_oid = lo_import_with_oid(pgsql, file_in, wanted_oid); if (returned_oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(returned_oid); #endif } returned_oid = lo_import(pgsql, file_in); if (returned_oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(returned_oid); } \/* }}} *\/ \/* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename) Export large object direct to filesystem *\/ PHP_FUNCTION(pg_lo_export) { zval *pgsql_link = NULL; char *file_out, *oid_string, *end_ptr; size_t oid_strlen; int id = -1; size_t name_len; zend_long oid_long; Oid oid; PGconn *pgsql; int argc = ZEND_NUM_ARGS(); \/* allow string to handle large OID value correctly *\/ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"rlp\", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL, E_NOTICE, \"Invalid OID specified\"); RETURN_FALSE; } oid = (Oid)oid_long; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"rss\", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { \/* wrong integer format *\/ php_error_docref(NULL, E_NOTICE, \"Wrong OID value passed\"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"lp\", &oid_long, &file_out, &name_len) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL, E_NOTICE, \"Invalid OID specified\"); RETURN_FALSE; } oid = (Oid)oid_long; id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"sp\", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { \/* wrong integer format *\/ php_error_docref(NULL, E_NOTICE, \"Wrong OID value passed\"); RETURN_FALSE; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"spr\", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { \/* wrong integer format *\/ php_error_docref(NULL, E_NOTICE, \"Wrong OID value passed\"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, \"lpr\", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) { php_error_docref(NULL, E_NOTICE, \"Old API is used\"); if (oid_long <= InvalidOid) { php_error_docref(NULL, E_NOTICE, \"Invalid OID specified\"); RETURN_FALSE; } oid = (Oid)oid_long; } else { php_error_docref(NULL, E_WARNING, \"Requires 2 or 3 arguments\"); RETURN_FALSE; } if (php_check_open_basedir(file_out)) { RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (lo_export(pgsql, oid, file_out) == -1) { RETURN_FALSE; } RETURN_TRUE; } \/* }}} *\/ \/* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence]) Seeks position of large object *\/ PHP_FUNCTION(pg_lo_seek) { zval *pgsql_id = NULL; zend_long result, offset = 0, whence = SEEK_CUR; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, \"rl|l\", &pgsql_id, &offset, &whence) == FAILURE) { return; } if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) { php_error_docref(NULL, E_WARNING, \"Invalid whence parameter\"); return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, \"PostgreSQL large object\", le_lofp); #if HAVE_PG_LO64 if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) { result = lo_lseek64((PGconn *)pgsql->conn, pgsql->lofd, offset, (int)whence); } else { result = lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, (int)offset, (int)whence); } #else result = lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence); #endif if (result > -1) { RETURN_TRUE; } else { RETURN_FALSE; } } \/* }}} *\/ \/* {{{ proto int pg_lo_tell(resource large_object) Returns current position of large object *\/ PHP_FUNCTION(pg_lo_tell) { zval *pgsql_id = NULL; zend_long offset = 0; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, \"r\", &pgsql_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, \"PostgreSQL large object\", le_lofp); #if HAVE_PG_LO64 if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) { offset = lo_tell64((PGconn *)pgsql->conn, pgsql->lofd); } else { offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd); } #else offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd); #endif RETURN_LONG(offset); } \/* }}} *\/ #if HAVE_PG_LO_TRUNCATE \/* {{{ proto bool pg_lo_truncate(resource large_object, int size) Truncate large object to size *\/ PHP_FUNCTION(pg_lo_truncate) { zval *pgsql_id = NULL; size_t size; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); int result; if (zend_parse_parameters(argc, \"rl\", &pgsql_id, &size) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, \"PostgreSQL large object\", le_lofp); #if HAVE_PG_LO64 if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) { result = lo_truncate64((PGconn *)pgsql->conn, pgsql->lofd, size); } else { result = lo_truncate((PGconn *)pgsql->conn, pgsql->lofd, size); } #else result = lo_truncate((PGconn *)pgsql->conn, pgsql->lofd, size); #endif if (!result) { RETURN_TRUE; } else { RETURN_FALSE; } } \/* }}} *\/ #endif #if HAVE_PQSETERRORVERBOSITY \/* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity) Set error verbosity *\/ PHP_FUNCTION(pg_set_error_verbosity) { zval *pgsql_link = NULL; zend_long verbosity; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (argc == 1) { if (zend_parse_parameters(argc, \"l\", &verbosity) == FAILURE) { return; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc, \"rl\", &pgsql_link, &verbosity) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (verbosity & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) { RETURN_LONG(PQsetErrorVerbosity(pgsql, verbosity)); } else { RETURN_FALSE; } } \/* }}} *\/ #endif #ifdef HAVE_PQCLIENTENCODING \/* {{{ proto int pg_set_client_encoding([resource connection,] string encoding) Set client encoding *\/ PHP_FUNCTION(pg_set_client_encoding) { char *encoding; size_t encoding_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (argc == 1) { if (zend_parse_parameters(argc, \"s\", &encoding, &encoding_len) == FAILURE) { return; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc, \"rs\", &pgsql_link, &encoding, &encoding_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); RETURN_LONG(PQsetClientEncoding(pgsql, encoding)); } \/* }}} *\/ \/* {{{ proto string pg_client_encoding([resource connection]) Get the current client encoding *\/ PHP_FUNCTION(pg_client_encoding) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (zend_parse_parameters(argc, \"|r\", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); \/* Just do the same as found in PostgreSQL sources... *\/ RETURN_STRING((char *) pg_encoding_to_char(PQclientEncoding(pgsql))); } \/* }}} *\/ #endif #if !HAVE_PQGETCOPYDATA #define COPYBUFSIZ 8192 #endif \/* {{{ proto bool pg_end_copy([resource connection]) Sync with backend. Completes the Copy command *\/ PHP_FUNCTION(pg_end_copy) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; int result = 0; if (zend_parse_parameters(argc, \"|r\", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); result = PQendcopy(pgsql); if (result!=0) { PHP_PQ_ERROR(\"Query failed: %s\", pgsql); RETURN_FALSE; } RETURN_TRUE; } \/* }}} *\/ \/* {{{ proto bool pg_put_line([resource connection,] string query) Send null-terminated string to backend server*\/ PHP_FUNCTION(pg_put_line) { char *query; zval *pgsql_link = NULL; size_t query_len; int id = -1; PGconn *pgsql; int result = 0, argc = ZEND_NUM_ARGS(); if (argc == 1) { if (zend_parse_parameters(argc, \"s\", &query, &query_len) == FAILURE) { return; } id = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc, \"rs\", &pgsql_link, &query, &query_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); result = PQputline(pgsql, query); if (result==EOF) { PHP_PQ_ERROR(\"Query failed: %s\", pgsql); RETURN_FALSE; } RETURN_TRUE; } \/* }}} *\/ \/* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]]) Copy table to array *\/ PHP_FUNCTION(pg_copy_to) { zval *pgsql_link; char *table_name, *pg_delim = NULL, *pg_null_as = NULL; size_t table_name_len, pg_delim_len, pg_null_as_len, free_pg_null = 0; char *query; int id = -1; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; int copydone = 0; #if !HAVE_PQGETCOPYDATA char copybuf[COPYBUFSIZ]; #endif char *csv = (char *)NULL; int ret; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, \"rs|ss\", &pgsql_link, &table_name, &table_name_len, &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) { return; } if (!pg_delim) { pg_delim = \"\\t\"; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (!pg_null_as) { pg_null_as = estrdup(\"\\\\\\\\N\"); free_pg_null = 1; } spprintf(&query, 0, \"COPY %s TO STDOUT DELIMITERS E'%c' WITH NULL AS E'%s'\", table_name, *pg_delim, pg_null_as); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } pgsql_result = PQexec(pgsql, query); if (free_pg_null) { efree(pg_null_as); } efree(query); if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_COPY_OUT: if (pgsql_result) { PQclear(pgsql_result); array_init(return_value); #if HAVE_PQGETCOPYDATA while (!copydone) { ret = PQgetCopyData(pgsql, &csv, 0); switch (ret) { case -1: copydone = 1; break; case 0: case -2: PHP_PQ_ERROR(\"getline failed: %s\", pgsql); RETURN_FALSE; break; default: add_next_index_string(return_value, csv); PQfreemem(csv); break; } } #else while (!copydone) { if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) { PHP_PQ_ERROR(\"getline failed: %s\", pgsql); RETURN_FALSE; } if (copybuf[0] == '\\\\' && copybuf[1] == '.' && copybuf[2] == '\\0') { copydone = 1; } else { if (csv == (char *)NULL) { csv = estrdup(copybuf); } else { csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1)); strcat(csv, copybuf); } switch (ret) { case EOF: copydone = 1; case 0: add_next_index_string(return_value, csv); efree(csv); csv = (char *)NULL; break; case 1: break; } } } if (PQendcopy(pgsql)) { PHP_PQ_ERROR(\"endcopy failed: %s\", pgsql); RETURN_FALSE; } #endif while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } } else { PQclear(pgsql_result); RETURN_FALSE; } break; default: PQclear(pgsql_result); PHP_PQ_ERROR(\"Copy command failed: %s\", pgsql); RETURN_FALSE; break; } } \/* }}} *\/ \/* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]]) Copy table from array *\/ PHP_FUNCTION(pg_copy_from) { zval *pgsql_link = NULL, *pg_rows; zval *tmp; char *table_name, *pg_delim = NULL, *pg_null_as = NULL; size_t table_name_len, pg_delim_len, pg_null_as_len; int pg_null_as_free = 0; char *query; int id = -1; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, \"rsa|ss\", &pgsql_link, &table_name, &table_name_len, &pg_rows, &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) { return; } if (!pg_delim) { pg_delim = \"\\t\"; } if (!pg_null_as) { pg_null_as = estrdup(\"\\\\\\\\N\"); pg_null_as_free = 1; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); spprintf(&query, 0, \"COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'\", table_name, *pg_delim, pg_null_as); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } pgsql_result = PQexec(pgsql, query); if (pg_null_as_free) { efree(pg_null_as); } efree(query); if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_COPY_IN: if (pgsql_result) { int command_failed = 0; PQclear(pgsql_result); #if HAVE_PQPUTCOPYDATA ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pg_rows), tmp) { convert_to_string_ex(tmp); query = (char *)emalloc(Z_STRLEN_P(tmp) + 2); strlcpy(query, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp) + 2); if(Z_STRLEN_P(tmp) > 0 && *(query + Z_STRLEN_P(tmp) - 1) != '\\n') { strlcat(query, \"\\n\", Z_STRLEN_P(tmp) + 2); } if (PQputCopyData(pgsql, query, (int)strlen(query)) != 1) { efree(query); PHP_PQ_ERROR(\"copy failed: %s\", pgsql); RETURN_FALSE; } efree(query); } ZEND_HASH_FOREACH_END(); if (PQputCopyEnd(pgsql, NULL) != 1) { PHP_PQ_ERROR(\"putcopyend failed: %s\", pgsql); RETURN_FALSE; } #else ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pg_rows), tmp) { convert_to_string_ex(tmp); query = (char *)emalloc(Z_STRLEN_P(tmp) + 2); strlcpy(query, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp) + 2); if(Z_STRLEN_P(tmp) > 0 && *(query + Z_STRLEN_P(tmp) - 1) != '\\n') { strlcat(query, \"\\n\", Z_STRLEN_P(tmp) + 2); } if (PQputline(pgsql, query)==EOF) { efree(query); PHP_PQ_ERROR(\"copy failed: %s\", pgsql); RETURN_FALSE; } efree(query); } ZEND_HASH_FOREACH_END(); if (PQputline(pgsql, \"\\\\.\\n\") == EOF) { PHP_PQ_ERROR(\"putline failed: %s\", pgsql); RETURN_FALSE; } if (PQendcopy(pgsql)) { PHP_PQ_ERROR(\"endcopy failed: %s\", pgsql); RETURN_FALSE; } #endif while ((pgsql_result = PQgetResult(pgsql))) { if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) { PHP_PQ_ERROR(\"Copy command failed: %s\", pgsql); command_failed = 1; } PQclear(pgsql_result); } if (command_failed) { RETURN_FALSE; } } else { PQclear(pgsql_result); RETURN_FALSE; } RETURN_TRUE; break; default: PQclear(pgsql_result); PHP_PQ_ERROR(\"Copy command failed: %s\", pgsql); RETURN_FALSE; break; } } \/* }}} *\/ #ifdef HAVE_PQESCAPE \/* {{{ proto string pg_escape_string([resource connection,] string data) Escape string for text\/char type *\/ PHP_FUNCTION(pg_escape_string) { zend_string *from = NULL, *to = NULL; zval *pgsql_link; #ifdef HAVE_PQESCAPE_CONN PGconn *pgsql; #endif int id = -1; switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS(), \"S\", &from) == FAILURE) { return; } pgsql_link = NULL; id = FETCH_DEFAULT_LINK(); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rS\", &pgsql_link, &from) == FAILURE) { return; } break; } to = zend_string_alloc(from->len * 2, 0); #ifdef HAVE_PQESCAPE_CONN if (pgsql_link != NULL || id != -1) { ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); to->len = PQescapeStringConn(pgsql, to->val, from->val, from->len, NULL); } else #endif { to->len = PQescapeString(to->val, from->val, from->len); } to = zend_string_realloc(to, to->len, 0); RETURN_STR(to); } \/* }}} *\/ \/* {{{ proto string pg_escape_bytea([resource connection,] string data) Escape binary for bytea type *\/ PHP_FUNCTION(pg_escape_bytea) { char *from = NULL, *to = NULL; size_t to_len; size_t from_len; int id = -1; #ifdef HAVE_PQESCAPE_BYTEA_CONN PGconn *pgsql; #endif zval *pgsql_link; switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &from, &from_len) == FAILURE) { return; } pgsql_link = NULL; id = FETCH_DEFAULT_LINK(); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rs\", &pgsql_link, &from, &from_len) == FAILURE) { return; } break; } #ifdef HAVE_PQESCAPE_BYTEA_CONN if (pgsql_link != NULL || id != -1) { ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); to = (char *)PQescapeByteaConn(pgsql, (unsigned char *)from, (size_t)from_len, &to_len); } else #endif to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len); RETVAL_STRINGL(to, to_len-1); \/* to_len includes additional '\\0' *\/ } \/* }}} *\/ #if !HAVE_PQUNESCAPEBYTEA \/* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users. Renamed to php_pgsql_unescape_bytea() *\/ \/* * PQunescapeBytea - converts the null terminated string representation * of a bytea, strtext, into binary, filling a buffer. It returns a * pointer to the buffer which is NULL on error, and the size of the * buffer in retbuflen. The pointer may subsequently be used as an * argument to the function free(3). It is the reverse of PQescapeBytea. * * The following transformations are reversed: * '\\0' == ASCII 0 == \\000 * '\\'' == ASCII 39 == \\' * '\\\\' == ASCII 92 == \\\\ * * States: * 0 normal 0->1->2->3->4 * 1 \\ 1->5 * 2 \\0 1->6 * 3 \\00 * 4 \\000 * 5 \\' * 6 \\\\ *\/ static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen) \/* {{{ *\/ { size_t buflen; unsigned char *buffer, *sp, *bp; unsigned int state = 0; if (strtext == NULL) return NULL; buflen = strlen(strtext); \/* will shrink, also we discover if * strtext *\/ buffer = (unsigned char *) emalloc(buflen); \/* isn't NULL terminated *\/ for (bp = buffer, sp = strtext; *sp != '\\0'; bp++, sp++) { switch (state) { case 0: if (*sp == '\\\\') state = 1; *bp = *sp; break; case 1: if (*sp == '\\'') \/* state=5 *\/ { \/* replace \\' with 39 *\/ bp--; *bp = '\\''; buflen--; state = 0; } else if (*sp == '\\\\') \/* state=6 *\/ { \/* replace \\\\ with 92 *\/ bp--; *bp = '\\\\'; buflen--; state = 0; } else { if (isdigit(*sp)) state = 2; else state = 0; *bp = *sp; } break; case 2: if (isdigit(*sp)) state = 3; else state = 0; *bp = *sp; break; case 3: if (isdigit(*sp)) \/* state=4 *\/ { unsigned char *start, *end, buf[4]; \/* 000 + '\\0' *\/ bp -= 3; memcpy(buf, sp-2, 3); buf[3] = '\\0'; start = buf; *bp = (unsigned char)strtoul(start, (char **)&end, 8); buflen -= 3; state = 0; } else { *bp = *sp; state = 0; } break; } } buffer = erealloc(buffer, buflen+1); buffer[buflen] = '\\0'; *retbuflen = buflen; return buffer; } \/* }}} *\/ #endif \/* {{{ proto string pg_unescape_bytea(string data) Unescape binary for bytea type *\/ PHP_FUNCTION(pg_unescape_bytea) { char *from = NULL, *to = NULL, *tmp = NULL; size_t to_len; size_t from_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &from, &from_len) == FAILURE) { return; } #if HAVE_PQUNESCAPEBYTEA tmp = (char *)PQunescapeBytea((unsigned char*)from, &to_len); to = estrndup(tmp, to_len); PQfreemem(tmp); #else to = (char *)php_pgsql_unescape_bytea((unsigned char*)from, &to_len); #endif if (!to) { php_error_docref(NULL, E_WARNING,\"Invalid parameter\"); RETURN_FALSE; } RETVAL_STRINGL(to, to_len); efree(to); } \/* }}} *\/ #endif #ifdef HAVE_PQESCAPE static void php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAMETERS, int escape_literal) \/* {{{ *\/ { char *from = NULL; zval *pgsql_link = NULL; PGconn *pgsql; size_t from_len; int id = -1; char *tmp; switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &from, &from_len) == FAILURE) { return; } pgsql_link = NULL; id = FETCH_DEFAULT_LINK(); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rs\", &pgsql_link, &from, &from_len) == FAILURE) { return; } break; } if (pgsql_link == NULL && id == -1) { php_error_docref(NULL, E_WARNING,\"Cannot get default pgsql link\"); RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (pgsql == NULL) { php_error_docref(NULL, E_WARNING,\"Cannot get pgsql link\"); RETURN_FALSE; } if (escape_literal) { tmp = PGSQLescapeLiteral(pgsql, from, (size_t)from_len); } else { tmp = PGSQLescapeIdentifier(pgsql, from, (size_t)from_len); } if (!tmp) { php_error_docref(NULL, E_WARNING,\"Failed to escape\"); RETURN_FALSE; } RETVAL_STRING(tmp); PGSQLfree(tmp); } \/* }}} *\/ \/* {{{ proto string pg_escape_literal([resource connection,] string data) Escape parameter as string literal (i.e. parameter) *\/ PHP_FUNCTION(pg_escape_literal) { php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } \/* }}} *\/ \/* {{{ proto string pg_escape_identifier([resource connection,] string data) Escape identifier (i.e. table name, field name) *\/ PHP_FUNCTION(pg_escape_identifier) { php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } \/* }}} *\/ #endif \/* {{{ proto string pg_result_error(resource result) Get error message associated with result *\/ PHP_FUNCTION(pg_result_error) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; char *err = NULL; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"r\", &result) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; if (!pgsql_result) { RETURN_FALSE; } err = (char *)PQresultErrorMessage(pgsql_result); RETURN_STRING(err); } \/* }}} *\/ #if HAVE_PQRESULTERRORFIELD \/* {{{ proto string pg_result_error_field(resource result, int fieldcode) Get error message field associated with result *\/ PHP_FUNCTION(pg_result_error_field) { zval *result; zend_long fieldcode; PGresult *pgsql_result; pgsql_result_handle *pg_result; char *field = NULL; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"rl\", &result, &fieldcode) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; if (!pgsql_result) { RETURN_FALSE; } if (fieldcode & (PG_DIAG_SEVERITY|PG_DIAG_SQLSTATE|PG_DIAG_MESSAGE_PRIMARY|PG_DIAG_MESSAGE_DETAIL |PG_DIAG_MESSAGE_HINT|PG_DIAG_STATEMENT_POSITION #if PG_DIAG_INTERNAL_POSITION |PG_DIAG_INTERNAL_POSITION #endif #if PG_DIAG_INTERNAL_QUERY |PG_DIAG_INTERNAL_QUERY #endif |PG_DIAG_CONTEXT|PG_DIAG_SOURCE_FILE|PG_DIAG_SOURCE_LINE |PG_DIAG_SOURCE_FUNCTION)) { field = (char *)PQresultErrorField(pgsql_result, (int)fieldcode); if (field == NULL) { RETURN_NULL(); } else { RETURN_STRING(field); } } else { RETURN_FALSE; } } \/* }}} *\/ #endif \/* {{{ proto int pg_connection_status(resource connection) Get connection status *\/ PHP_FUNCTION(pg_connection_status) { zval *pgsql_link = NULL; int id = -1; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"r\", &pgsql_link) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); RETURN_LONG(PQstatus(pgsql)); } \/* }}} *\/ #if HAVE_PGTRANSACTIONSTATUS \/* {{{ proto int pg_transaction_status(resource connection) Get transaction status *\/ PHP_FUNCTION(pg_transaction_status) { zval *pgsql_link = NULL; int id = -1; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"r\", &pgsql_link) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); RETURN_LONG(PQtransactionStatus(pgsql)); } #endif \/* }}} *\/ \/* {{{ proto bool pg_connection_reset(resource connection) Reset connection (reconnect) *\/ PHP_FUNCTION(pg_connection_reset) { zval *pgsql_link; int id = -1; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"r\", &pgsql_link) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); PQreset(pgsql); if (PQstatus(pgsql) == CONNECTION_BAD) { RETURN_FALSE; } RETURN_TRUE; } \/* }}} *\/ #define PHP_PG_ASYNC_IS_BUSY 1 #define PHP_PG_ASYNC_REQUEST_CANCEL 2 \/* {{{ php_pgsql_flush_query *\/ static int php_pgsql_flush_query(PGconn *pgsql) { PGresult *res; int leftover = 0; if (PQ_SETNONBLOCKING(pgsql, 1)) { php_error_docref(NULL, E_NOTICE,\"Cannot set connection to nonblocking mode\"); return -1; } while ((res = PQgetResult(pgsql))) { PQclear(res); leftover++; } PQ_SETNONBLOCKING(pgsql, 0); return leftover; } \/* }}} *\/ \/* {{{ php_pgsql_do_async *\/ static void php_pgsql_do_async(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *pgsql_link; int id = -1; PGconn *pgsql; PGresult *pgsql_result; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"r\", &pgsql_link) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 1)) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to nonblocking mode\"); RETURN_FALSE; } switch(entry_type) { case PHP_PG_ASYNC_IS_BUSY: PQconsumeInput(pgsql); RETVAL_LONG(PQisBusy(pgsql)); break; case PHP_PG_ASYNC_REQUEST_CANCEL: RETVAL_LONG(PQrequestCancel(pgsql)); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } break; default: php_error_docref(NULL, E_ERROR, \"PostgreSQL module error, please report this error\"); break; } if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to blocking mode\"); } convert_to_boolean_ex(return_value); } \/* }}} *\/ \/* {{{ proto bool pg_cancel_query(resource connection) Cancel request *\/ PHP_FUNCTION(pg_cancel_query) { php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_REQUEST_CANCEL); } \/* }}} *\/ \/* {{{ proto bool pg_connection_busy(resource connection) Get connection is busy or not *\/ PHP_FUNCTION(pg_connection_busy) { php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_IS_BUSY); } \/* }}} *\/ static int _php_pgsql_link_has_results(PGconn *pgsql) \/* {{{ *\/ { PGresult *result; while ((result = PQgetResult(pgsql))) { PQclear(result); return 1; } return 0; } \/* }}} *\/ \/* {{{ proto bool pg_send_query(resource connection, string query) Send asynchronous query *\/ PHP_FUNCTION(pg_send_query) { zval *pgsql_link; char *query; size_t len; int id = -1; PGconn *pgsql; int is_non_blocking; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rs\", &pgsql_link, &query, &len) == FAILURE) { return; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); is_non_blocking = PQisnonblocking(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to nonblocking mode\"); RETURN_FALSE; } if (_php_pgsql_link_has_results(pgsql)) { php_error_docref(NULL, E_NOTICE, \"There are results on this connection. Call pg_get_result() until it returns FALSE\"); } if (is_non_blocking) { if (!PQsendQuery(pgsql, query)) { RETURN_FALSE; } ret = PQflush(pgsql); } else { if (!PQsendQuery(pgsql, query)) { if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQreset(pgsql); } if (!PQsendQuery(pgsql, query)) { RETURN_FALSE; } } \/* Wait to finish sending buffer *\/ while ((ret = PQflush(pgsql))) { if (ret == -1) { php_error_docref(NULL, E_NOTICE, \"Could not empty PostgreSQL send buffer\"); break; } usleep(10000); } if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to blocking mode\"); } } if (ret == 0) { RETURN_TRUE; } else if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(0); } } \/* }}} *\/ #if HAVE_PQSENDQUERYPARAMS \/* {{{ proto bool pg_send_query_params(resource connection, string query, array params) Send asynchronous parameterized query *\/ PHP_FUNCTION(pg_send_query_params) { zval *pgsql_link, *pv_param_arr, *tmp; int num_params = 0; char **params = NULL; char *query; size_t query_len; int id = -1; PGconn *pgsql; int is_non_blocking; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rsa\/\", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) { return; } if (pgsql_link == NULL) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); is_non_blocking = PQisnonblocking(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to nonblocking mode\"); RETURN_FALSE; } if (_php_pgsql_link_has_results(pgsql)) { php_error_docref(NULL, E_NOTICE, \"There are results on this connection. Call pg_get_result() until it returns FALSE\"); } num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) { if (Z_TYPE_P(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val; ZVAL_COPY(&tmp_val, tmp); convert_to_string(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL, E_WARNING,\"Error converting parameter\"); zval_ptr_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_ptr_dtor(&tmp_val); } i++; } ZEND_HASH_FOREACH_END(); } if (PQsendQueryParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0)) { _php_pgsql_free_params(params, num_params); } else if (is_non_blocking) { _php_pgsql_free_params(params, num_params); RETURN_FALSE; } else { if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQreset(pgsql); } if (!PQsendQueryParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0)) { _php_pgsql_free_params(params, num_params); RETURN_FALSE; } } if (is_non_blocking) { ret = PQflush(pgsql); } else { \/* Wait to finish sending buffer *\/ while ((ret = PQflush(pgsql))) { if (ret == -1) { php_error_docref(NULL, E_NOTICE, \"Could not empty PostgreSQL send buffer\"); break; } usleep(10000); } if (PQ_SETNONBLOCKING(pgsql, 0) != 0) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to blocking mode\"); } } if (ret == 0) { RETURN_TRUE; } else if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(0); } } \/* }}} *\/ #endif #if HAVE_PQSENDPREPARE \/* {{{ proto bool pg_send_prepare(resource connection, string stmtname, string query) Asynchronously prepare a query for future execution *\/ PHP_FUNCTION(pg_send_prepare) { zval *pgsql_link; char *query, *stmtname; size_t stmtname_len, query_len; int id = -1; PGconn *pgsql; int is_non_blocking; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rss\", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } if (pgsql_link == NULL) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); is_non_blocking = PQisnonblocking(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to nonblocking mode\"); RETURN_FALSE; } if (_php_pgsql_link_has_results(pgsql)) { php_error_docref(NULL, E_NOTICE, \"There are results on this connection. Call pg_get_result() until it returns FALSE\"); } if (!PQsendPrepare(pgsql, stmtname, query, 0, NULL)) { if (is_non_blocking) { RETURN_FALSE; } else { if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQreset(pgsql); } if (!PQsendPrepare(pgsql, stmtname, query, 0, NULL)) { RETURN_FALSE; } } } if (is_non_blocking) { ret = PQflush(pgsql); } else { \/* Wait to finish sending buffer *\/ while ((ret = PQflush(pgsql))) { if (ret == -1) { php_error_docref(NULL, E_NOTICE, \"Could not empty PostgreSQL send buffer\"); break; } usleep(10000); } if (PQ_SETNONBLOCKING(pgsql, 0) != 0) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to blocking mode\"); } } if (ret == 0) { RETURN_TRUE; } else if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(0); } } \/* }}} *\/ #endif #if HAVE_PQSENDQUERYPREPARED \/* {{{ proto bool pg_send_execute(resource connection, string stmtname, array params) Executes prevriously prepared stmtname asynchronously *\/ PHP_FUNCTION(pg_send_execute) { zval *pgsql_link; zval *pv_param_arr, *tmp; int num_params = 0; char **params = NULL; char *stmtname; size_t stmtname_len; int id = -1; PGconn *pgsql; int is_non_blocking; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"rsa\", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) { return; } if (pgsql_link == NULL) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); is_non_blocking = PQisnonblocking(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to nonblocking mode\"); RETURN_FALSE; } if (_php_pgsql_link_has_results(pgsql)) { php_error_docref(NULL, E_NOTICE, \"There are results on this connection. Call pg_get_result() until it returns FALSE\"); } num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) { if (Z_TYPE_P(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val; ZVAL_COPY(&tmp_val, tmp); convert_to_string(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL, E_WARNING,\"Error converting parameter\"); zval_ptr_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_ptr_dtor(&tmp_val); } i++; } ZEND_HASH_FOREACH_END(); } if (PQsendQueryPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0)) { _php_pgsql_free_params(params, num_params); } else if (is_non_blocking) { _php_pgsql_free_params(params, num_params); RETURN_FALSE; } else { if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQreset(pgsql); } if (!PQsendQueryPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0)) { _php_pgsql_free_params(params, num_params); RETURN_FALSE; } } if (is_non_blocking) { ret = PQflush(pgsql); } else { \/* Wait to finish sending buffer *\/ while ((ret = PQflush(pgsql))) { if (ret == -1) { php_error_docref(NULL, E_NOTICE, \"Could not empty PostgreSQL send buffer\"); break; } usleep(10000); } if (PQ_SETNONBLOCKING(pgsql, 0) != 0) { php_error_docref(NULL, E_NOTICE, \"Cannot set connection to blocking mode\"); } } if (ret == 0) { RETURN_TRUE; } else if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(0); } } \/* }}} *\/ #endif \/* {{{ proto resource pg_get_result(resource connection) Get asynchronous query result *\/ PHP_FUNCTION(pg_get_result) { zval *pgsql_link; int id = -1; PGconn *pgsql; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"r\", &pgsql_link) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); pgsql_result = PQgetResult(pgsql); if (!pgsql_result) { \/* no result *\/ RETURN_FALSE; } pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } \/* }}} *\/ \/* {{{ proto mixed pg_result_status(resource result[, long result_type]) Get status of query result *\/ PHP_FUNCTION(pg_result_status) { zval *result; zend_long result_type = PGSQL_STATUS_LONG; ExecStatusType status; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"r|l\", &result, &result_type) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, \"PostgreSQL result\", le_result); pgsql_result = pg_result->result; if (result_type == PGSQL_STATUS_LONG) { status = PQresultStatus(pgsql_result); RETURN_LONG((int)status); } else if (result_type == PGSQL_STATUS_STRING) { RETURN_STRING(PQcmdStatus(pgsql_result)); } else { php_error_docref(NULL, E_WARNING, \"Optional 2nd parameter should be PGSQL_STATUS_LONG or PGSQL_STATUS_STRING\"); RETURN_FALSE; } } \/* }}} *\/ \/* {{{ proto array pg_get_notify([resource connection[, result_type]]) Get asynchronous notification *\/ PHP_FUNCTION(pg_get_notify) { zval *pgsql_link; int id = -1; zend_long result_type = PGSQL_ASSOC; PGconn *pgsql; PGnotify *pgsql_notify; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"r|l\", &pgsql_link, &result_type) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, \"PostgreSQL link\", le_link, le_plink); if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL, E_WARNING, \"Invalid result type\"); RETURN_FALSE; } PQconsumeInput(pgsql); pgsql_notify = PQnotifies(pgsql); if (!pgsql_notify) { \/* no notify message *\/ RETURN_FALSE; } array_init(return_value); if (result_type & PGSQL_NUM) { add_index_string(return_value, 0, pgsql_notify->relname); add_index_long(return_value, 1, pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, \"server_version\")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_index_string(return_value, 2, pgsql_notify->extra); #endif } } if (result_type & PGSQL_ASSOC) { add_assoc_string(return_value, \"message\", pgsql_notify->relname); add_assoc_long(return_value, \"pid\", pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, \"server_version\")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_assoc_string(return_value, \"payload\", pgsql_notify->extra); #endif } } PQfreemem(pgsql_notify); } \/* }}} *\/","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":249610,"input":"void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_present = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_present = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; uchar *table_buf_0x0116; ushort table_buf_0x0116_present = 0; INT64 fsize = ifp->size(); #endif \/* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. *\/ if (!strncmp(make, \"Nokia\", 5)) return; fread(buf, 1, 10, ifp); \/* printf(\"===>>buf: 0x\"); for (int i = 0; i < sizeof buf; i ++) { printf(\"%02x\", buf[i]); } putchar('\\n'); *\/ if (!strncmp(buf, \"KDK\", 3) || \/* these aren't TIFF tables *\/ !strncmp(buf, \"VER\", 3) || !strncmp(buf, \"IIII\", 4) || !strncmp(buf, \"MMMM\", 4)) return; if (!strncmp(buf, \"KC\", 2) || \/* Konica KD-400Z, KD-510Z *\/ !strncmp(buf, \"MLY\", 3)) { \/* Minolta DiMAGE G series *\/ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, \"Nikon\")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, \"OLYMPUS\") || !strcmp(buf, \"PENTAX \")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, \"SONY\", 4) || !strcmp(buf, \"Panasonic\")) { goto nf; } else if (!strncmp(buf, \"FUJIFILM\", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, \"OLYMP\") || !strcmp(buf, \"LEICA\") || !strcmp(buf, \"Ricoh\") || !strcmp(buf, \"EPSON\")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, \"AOC\") || !strcmp(buf, \"QVC\")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, \"SAMSUNG\", 7)) base = ftell(ifp); } \/\/ adjust pos & base for Leica M8\/M9\/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, \"LEICA\", 5)) { if (!strncmp(model, \"M8\", 2) || !strncasecmp(model, \"Leica M8\", 8) || !strncasecmp(model, \"LEICA X\", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, \"LEICA M (Typ 240)\", 17)) { base = 0; } else if (!strncmp(model, \"M9\", 2) || !strncasecmp(model, \"Leica M9\", 8) || !strncasecmp(model, \"M Monochrom\", 11) || !strncasecmp(model, \"Leica M Monochrom\", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, \"LEICA T\", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, \"LEICA SL\", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) continue; if (!strncmp(make, \"Canon\", 5)) { if (tag == 0x000d && len < 256000) \/\/ camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16,len*4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) \/\/ Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, \"FUJI\", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), \"%s %s\", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, \"%2x\", &c); j += 2) ystr[j \/ 2] = c; ystr[ynum_len \/ 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), \"%s %s %d:%s:%s\", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), \"%s %d:%s:%s %s\", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), \"%s %s %d:%s:%s %s\", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, \"Hasselblad X1D\", 14) || !strncasecmp(model, \"Hasselblad H6D\", 14) || !strncasecmp(model, \"Hasselblad A6D\", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, \"LEICA\", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp (make, \"Leica Camera AG\", 15) && !strncmp (buf, \"LEICA\", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0) ) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, \"LEICA M\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, \"LEICA S\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, \"NIKON\", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) \/ (float)c; } else if (tag == 0x003b) \/\/ all 1s for regular exposures { imgdata.makernotes.nikon.ME_WB[0] = getreal(type); imgdata.makernotes.nikon.ME_WB[2] = getreal(type); imgdata.makernotes.nikon.ME_WB[1] = getreal(type); imgdata.makernotes.nikon.ME_WB[3] = getreal(type); } else if (tag == 0x0082) \/\/ lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) \/\/ lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) \/\/ lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) \/\/ lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 \/ c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops \/ 12.0f; } } else if (tag == 0x0093) \/\/ Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) \/\/ contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: \/\/ encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) \/\/ contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); \/\/ ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } } else if (!strncmp(make, \"OLYMPUS\", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) \/ 2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float) temp; else imgdata.other.CameraTemperature = (float) (temp-32) \/ 1.8f; if ((OlyID == 0x4434353933ULL) && \/\/ TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || \/\/ E-1 (OlyID == 0x5330303336ULL) || \/\/ E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(make, \"RICOH\", 5)) && !strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { \/\/ sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, \"%02x\", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, \"%8s\", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, \"%02x%02x%02x%02x\", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%02x%02x%02x%02x\", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, \"RICOH\", 5) && strncmp(model, \"PENTAX\", 6)) { if ((tag == 0x0005) && !strncmp(model, \"GXR\", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, \"GXR\", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(model, \"PENTAX\", 6) || (!strncmp(make, \"SAMSUNG\", 7) && dng_version)) && strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() \/ 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() \/ 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) \/ 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) \/ 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) \/\/ Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) \/ sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%d\", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) \/\/ Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, \" \"); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, \"SAMSUNG\", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, \"NX mini\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float) temp; if (get4() == 10) imgdata.other.CameraTemperature \/= 10.0f; } } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() \/ 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, \"SONY\", 4) || !strncasecmp(make, \"Konica\", 6) || !strncasecmp(make, \"Minolta\", 7) || (!strncasecmp(make, \"Hasselblad\", 10) && (!strncasecmp(model, \"Stellar\", 7) || !strncasecmp(model, \"Lunar\", 5) || !strncasecmp(model, \"Lusso\", 5) || !strncasecmp(model, \"HV\", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present, table_buf_0x0116, table_buf_0x0116_present, table_buf_0x9402, table_buf_0x9402_present, table_buf_0x9403, table_buf_0x9403_present, table_buf_0x9406, table_buf_0x9406_present); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, \"NIKON\") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, \"NIKON\") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * powf64(2.0f, float(cc) \/ 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i \/ 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i \/ 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short)i \/ -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, \"KONICA\", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, \"Canon\", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 \/* Canon rotation data is handled by EXIF.Orientation *\/ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = \"065\"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, \"Olympus\", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, \"E-410\", 5) || !strncasecmp(model, \"E-510\", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, \"v757-71\")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, \"v757-71\")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, \"NIKON\", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, \"NRW \", 4)) { fseek(ifp, strcmp(buf + 4, \"0100\") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, \"PENTAX\")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, \"D50\"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, \"%d\", serial); #endif } if (tag == 0x29 && type == 1) { \/\/ Canon PowerShot G9 c = wbi < 18 ? \"012347800000005896\"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, \"Samsung\", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { \/\/ shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = \"66666>666;6A;:;55\"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) \/\/ Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) \/\/ Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) \/\/ Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) \/\/ Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD \/\/ not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, \"NIKON\") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { \/* Nikon Capture Note *\/ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 \/ 0x10000; cam_mul[2] = get2() * 382 * 1.173 \/ 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, \"v757-71\")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) \/ 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) \/ 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) \/ 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() \/ 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() \/ 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() \/ 256.0; cam_mul[2] = get2() \/ 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD \/\/ IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) && ((type == 7) || (type == 13)) && !strncasecmp(make, \"Olympus\", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } \/\/ IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, \"OLYMP\", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, \"Samsung\", 7)) { if (tag == 0xa020) \/\/ get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) \/\/ get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } \/* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf (\"Samsung 0xa025 %d\\n\", i); } *\/ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) \/ 256.0; #endif if (tag == 0xa031 && len == 9) \/\/ get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) \/ 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { \/\/ Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":59877,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long) (((png_uint_32) p[0] << 24) | ((png_uint_32) p[1] << 16) | ((png_uint_32) p[2] << 8) | (png_uint_32) p[3]); mng_info->mng_height=(unsigned long) (((png_uint_32) p[4] << 24) | ((png_uint_32) p[5] << 16) | ((png_uint_32) p[6] << 8) | (png_uint_32) p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if (length < 2) { if (chunk) chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) (((png_uint_32) p[4] << 24) | ((png_uint_32) p[5] << 16) | ((png_uint_32) p[6] << 8) | (png_uint_32) p[7]); mng_info->y_off[object_id]=(ssize_t) (((png_uint_32) p[8] << 24) | ((png_uint_32) p[9] << 16) | ((png_uint_32) p[10] << 8) | (png_uint_32) p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (*p && ((p-chunk) < (ssize_t) length)) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) (((png_uint_32) p[0] << 24) | ((png_uint_32) p[1] << 16) | ((png_uint_32) p[2] << 8) | (png_uint_32) p[3]); basi_height=(unsigned long) (((png_uint_32) p[4] << 24) | ((png_uint_32) p[5] << 16) | ((png_uint_32) p[6] << 8) | (png_uint_32) p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":248870,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length_ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if (length < 2) { if (chunk) chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (*p && ((p-chunk) < (ssize_t) length)) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 13) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 15) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 17) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":202294,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char *name, s[2]; const char *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if ((image->storage_class != PseudoClass) && (image->colormap != (PixelInfo *) NULL)) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; if (image->depth != GetImageDepth(image,exception)) (void) SetImageDepth(image,image->depth,exception); for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *r; register Quantum *q; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < MagickMin(image->colors,256); i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { r=GetVirtualPixels(image,0,y,image->columns,1,exception); if (r == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,r) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image,r,opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,r,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image,r,opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,r) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image,r,transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,r); ping_trans_color.green=(unsigned short) GetPixelGreen(image,r); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,r); ping_trans_color.gray=(unsigned short) GetPixelGray(image,r); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,r,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,r,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,r,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,r,semitransparent+i) && GetPixelAlpha(image,r) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image,r,semitransparent+i); } } } r+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } if (number_opaque < 259) { for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != GetPixelGreen(image,r) || GetPixelRed(image,r) != GetPixelBlue(image,r)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != 0 && GetPixelRed(image,r) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,q); SetPixelAlpha(image,TransparentAlpha,q); } else SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR04PixelRGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR03RGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR02PixelBlue(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,q)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,q)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,q)) == 0x00 && GetPixelAlpha(image,q) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } (void) old_bit_depth; image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); \/* write orNT if image->orientation is defined *\/ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); \/* data length=1 *\/ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); \/* PNG uses Exif orientation values *\/ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(ping_pixels,0,rowbytes*sizeof(*ping_pixels)); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) || ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse)) { \/* Palette, Bilevel, or Opaque Monochrome *\/ QuantumType quantum_type; register const Quantum *p; quantum_type=RedQuantum; if (mng_info->IsPalette) { quantum_type=GrayQuantum; if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) quantum_type=IndexQuantum; } SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,ping_pixels,exception); if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"True","vulnerability_types":["Out-of-bounds Write"],"explanation":"In WriteOnePNGImage() of the PNG coder at coders\/png.c, an improper call to AcquireVirtualMemory() and memset() allows for an out-of-bounds write later when PopShortPixel() from MagickCore\/quantum-private.h is called. The patch fixes the calls by adding 256 to rowbytes. An attacker who is able to supply a specially crafted image could affect availability with a low impact to data integrity. This flaw affects ImageMagick versions prior to 6.9.10-68 and 7.0.8-68.","severity_level":"NoInfo","cwe":"CWE-787","cve":"CVE-2020-25664"}} -{"idx":213374,"input":"receive_msg(BOOL extract_recip) { int i; int rc = FAIL; int msg_size = 0; int process_info_len = Ustrlen(process_info); int error_rc = (error_handling == ERRORS_SENDER)? errors_sender_rc : EXIT_FAILURE; int header_size = 256; int start, end, domain; int id_resolution; int had_zero = 0; int prevlines_length = 0; register int ptr = 0; BOOL contains_resent_headers = FALSE; BOOL extracted_ignored = FALSE; BOOL first_line_ended_crlf = TRUE_UNSET; BOOL smtp_yield = TRUE; BOOL yield = FALSE; BOOL resents_exist = FALSE; uschar *resent_prefix = US\"\"; uschar *blackholed_by = NULL; uschar *blackhole_log_msg = US\"\"; enum {NOT_TRIED, TMP_REJ, PERM_REJ, ACCEPTED} cutthrough_done = NOT_TRIED; flock_t lock_data; error_block *bad_addresses = NULL; uschar *frozen_by = NULL; uschar *queued_by = NULL; uschar *errmsg; gstring * g; struct stat statbuf; \/* Final message to give to SMTP caller, and messages from ACLs *\/ uschar *smtp_reply = NULL; uschar *user_msg, *log_msg; \/* Working header pointers *\/ header_line *h, *next; \/* Flags for noting the existence of certain headers (only one left) *\/ BOOL date_header_exists = FALSE; \/* Pointers to receive the addresses of headers whose contents we need. *\/ header_line *from_header = NULL; header_line *subject_header = NULL; header_line *msgid_header = NULL; header_line *received_header; #ifdef EXPERIMENTAL_DMARC int dmarc_up = 0; #endif \/* EXPERIMENTAL_DMARC *\/ \/* Variables for use when building the Received: header. *\/ uschar *timestamp; int tslen; \/* Release any open files that might have been cached while preparing to accept the message - e.g. by verifying addresses - because reading a message might take a fair bit of real time. *\/ search_tidyup(); \/* Extracting the recipient list from an input file is incompatible with cutthrough delivery with the no-spool option. It shouldn't be possible to set up the combination, but just in case kill any ongoing connection. *\/ if (extract_recip || !smtp_input) cancel_cutthrough_connection(TRUE, US\"not smtp input\"); \/* Initialize the chain of headers by setting up a place-holder for Received: header. Temporarily mark it as \"old\", i.e. not to be used. We keep header_last pointing to the end of the chain to make adding headers simple. *\/ received_header = header_list = header_last = store_get(sizeof(header_line)); header_list->next = NULL; header_list->type = htype_old; header_list->text = NULL; header_list->slen = 0; \/* Control block for the next header to be read. *\/ next = store_get(sizeof(header_line)); next->text = store_get(header_size); \/* Initialize message id to be null (indicating no message read), and the header names list to be the normal list. Indicate there is no data file open yet, initialize the size and warning count, and deal with no size limit. *\/ message_id[0] = 0; data_file = NULL; data_fd = -1; spool_name = US\"\"; message_size = 0; warning_count = 0; received_count = 1; \/* For the one we will add *\/ if (thismessage_size_limit <= 0) thismessage_size_limit = INT_MAX; \/* While reading the message, the following counts are computed. *\/ message_linecount = body_linecount = body_zerocount = max_received_linelength = 0; #ifndef DISABLE_DKIM \/* Call into DKIM to set up the context. In CHUNKING mode we clear the dot-stuffing flag *\/ if (smtp_input && !smtp_batched_input && !dkim_disable_verify) dkim_exim_verify_init(chunking_state <= CHUNKING_OFFERED); #endif #ifdef EXPERIMENTAL_DMARC \/* initialize libopendmarc *\/ dmarc_up = dmarc_init(); #endif \/* Remember the time of reception. Exim uses time+pid for uniqueness of message ids, and fractions of a second are required. See the comments that precede the message id creation below. *\/ (void)gettimeofday(&message_id_tv, NULL); \/* For other uses of the received time we can operate with granularity of one second, and for that we use the global variable received_time. This is for things like ultimate message timeouts.XXX *\/ received_time = message_id_tv; \/* If SMTP input, set the special handler for timeouts. The alarm() calls happen in the smtp_getc() function when it refills its buffer. *\/ if (smtp_input) os_non_restarting_signal(SIGALRM, data_timeout_handler); \/* If not SMTP input, timeout happens only if configured, and we just set a single timeout for the whole message. *\/ else if (receive_timeout > 0) { os_non_restarting_signal(SIGALRM, data_timeout_handler); alarm(receive_timeout); } \/* SIGTERM and SIGINT are caught always. *\/ signal(SIGTERM, data_sigterm_sigint_handler); signal(SIGINT, data_sigterm_sigint_handler); \/* Header lines in messages are not supposed to be very long, though when unfolded, to: and cc: headers can take up a lot of store. We must also cope with the possibility of junk being thrown at us. Start by getting 256 bytes for storing the header, and extend this as necessary using string_cat(). To cope with total lunacies, impose an upper limit on the length of the header section of the message, as otherwise the store will fill up. We must also cope with the possibility of binary zeros in the data. Hence we cannot use fgets(). Folded header lines are joined into one string, leaving the '\\n' characters inside them, so that writing them out reproduces the input. Loop for each character of each header; the next structure for chaining the header is set up already, with ptr the offset of the next character in next->text. *\/ for (;;) { int ch = (receive_getc)(GETC_BUFFER_UNLIMITED); \/* If we hit EOF on a SMTP connection, it's an error, since incoming SMTP must have a correct \".\" terminator. *\/ if (ch == EOF && smtp_input \/* && !smtp_batched_input *\/) { smtp_reply = handle_lost_connection(US\" (header)\"); smtp_yield = FALSE; goto TIDYUP; \/* Skip to end of function *\/ } \/* See if we are at the current header's size limit - there must be at least four bytes left. This allows for the new character plus a zero, plus two for extra insertions when we are playing games with dots and carriage returns. If we are at the limit, extend the text buffer. This could have been done automatically using string_cat() but because this is a tightish loop storing only one character at a time, we choose to do it inline. Normally store_extend() will be able to extend the block; only at the end of a big store block will a copy be needed. To handle the case of very long headers (and sometimes lunatic messages can have ones that are 100s of K long) we call store_release() for strings that have been copied - if the string is at the start of a block (and therefore the only thing in it, because we aren't doing any other gets), the block gets freed. We can only do this because we know there are no other calls to store_get() going on. *\/ if (ptr >= header_size - 4) { int oldsize = header_size; \/* header_size += 256; *\/ header_size *= 2; if (!store_extend(next->text, oldsize, header_size)) { uschar *newtext = store_get(header_size); memcpy(newtext, next->text, ptr); store_release(next->text); next->text = newtext; } } \/* Cope with receiving a binary zero. There is dispute about whether these should be allowed in RFC 822 messages. The middle view is that they should not be allowed in headers, at least. Exim takes this attitude at the moment. We can't just stomp on them here, because we don't know that this line is a header yet. Set a flag to cause scanning later. *\/ if (ch == 0) had_zero++; \/* Test for termination. Lines in remote SMTP are terminated by CRLF, while those from data files use just LF. Treat LF in local SMTP input as a terminator too. Treat EOF as a line terminator always. *\/ if (ch == EOF) goto EOL; \/* FUDGE: There are sites out there that don't send CRs before their LFs, and other MTAs accept this. We are therefore forced into this \"liberalisation\" too, so we accept LF as a line terminator whatever the source of the message. However, if the first line of the message ended with a CRLF, we treat a bare LF specially by inserting a white space after it to ensure that the header line is not terminated. *\/ if (ch == '\\n') { if (first_line_ended_crlf == TRUE_UNSET) first_line_ended_crlf = FALSE; else if (first_line_ended_crlf) receive_ungetc(' '); goto EOL; } \/* This is not the end of the line. If this is SMTP input and this is the first character in the line and it is a \".\" character, ignore it. This implements the dot-doubling rule, though header lines starting with dots aren't exactly common. They are legal in RFC 822, though. If the following is CRLF or LF, this is the line that that terminates the entire message. We set message_ended to indicate this has happened (to prevent further reading), and break out of the loop, having freed the empty header, and set next = NULL to indicate no data line. *\/ if (ptr == 0 && ch == '.' && (smtp_input || dot_ends)) { ch = (receive_getc)(GETC_BUFFER_UNLIMITED); if (ch == '\\r') { ch = (receive_getc)(GETC_BUFFER_UNLIMITED); if (ch != '\\n') { receive_ungetc(ch); ch = '\\r'; \/* Revert to CR *\/ } } if (ch == '\\n') { message_ended = END_DOT; store_reset(next); next = NULL; break; \/* End character-reading loop *\/ } \/* For non-SMTP input, the dot at the start of the line was really a data character. What is now in ch is the following character. We guaranteed enough space for this above. *\/ if (!smtp_input) { next->text[ptr++] = '.'; message_size++; } } \/* If CR is immediately followed by LF, end the line, ignoring the CR, and remember this case if this is the first line ending. *\/ if (ch == '\\r') { ch = (receive_getc)(GETC_BUFFER_UNLIMITED); if (ch == '\\n') { if (first_line_ended_crlf == TRUE_UNSET) first_line_ended_crlf = TRUE; goto EOL; } \/* Otherwise, put back the character after CR, and turn the bare CR into LF SP. *\/ ch = (receive_ungetc)(ch); next->text[ptr++] = '\\n'; message_size++; ch = ' '; } \/* We have a data character for the header line. *\/ next->text[ptr++] = ch; \/* Add to buffer *\/ message_size++; \/* Total message size so far *\/ \/* Handle failure due to a humungously long header section. The >= allows for the terminating \\n. Add what we have so far onto the headers list so that it gets reflected in any error message, and back up the just-read character. *\/ if (message_size >= header_maxsize) { next->text[ptr] = 0; next->slen = ptr; next->type = htype_other; next->next = NULL; header_last->next = next; header_last = next; log_write(0, LOG_MAIN, \"ridiculously long message header received from \" \"%s (more than %d characters): message abandoned\", sender_host_unknown? sender_ident : sender_fullhost, header_maxsize); if (smtp_input) { smtp_reply = US\"552 Message header is ridiculously long\"; receive_swallow_smtp(); goto TIDYUP; \/* Skip to end of function *\/ } else { give_local_error(ERRMESS_VLONGHEADER, string_sprintf(\"message header longer than %d characters received: \" \"message not accepted\", header_maxsize), US\"\", error_rc, stdin, header_list->next); \/* Does not return *\/ } } continue; \/* With next input character *\/ \/* End of header line reached *\/ EOL: \/* Keep track of lines for BSMTP errors and overall message_linecount. *\/ receive_linecount++; message_linecount++; \/* Keep track of maximum line length *\/ if (ptr - prevlines_length > max_received_linelength) max_received_linelength = ptr - prevlines_length; prevlines_length = ptr + 1; \/* Now put in the terminating newline. There is always space for at least two more characters. *\/ next->text[ptr++] = '\\n'; message_size++; \/* A blank line signals the end of the headers; release the unwanted space and set next to NULL to indicate this. *\/ if (ptr == 1) { store_reset(next); next = NULL; break; } \/* There is data in the line; see if the next input character is a whitespace character. If it is, we have a continuation of this header line. There is always space for at least one character at this point. *\/ if (ch != EOF) { int nextch = (receive_getc)(GETC_BUFFER_UNLIMITED); if (nextch == ' ' || nextch == '\\t') { next->text[ptr++] = nextch; message_size++; continue; \/* Iterate the loop *\/ } else if (nextch != EOF) (receive_ungetc)(nextch); \/* For next time *\/ else ch = EOF; \/* Cause main loop to exit at end *\/ } \/* We have got to the real line end. Terminate the string and release store beyond it. If it turns out to be a real header, internal binary zeros will be squashed later. *\/ next->text[ptr] = 0; next->slen = ptr; store_reset(next->text + ptr + 1); \/* Check the running total size against the overall message size limit. We don't expect to fail here, but if the overall limit is set less than MESSAGE_ MAXSIZE and a big header is sent, we want to catch it. Just stop reading headers - the code to read the body will then also hit the buffer. *\/ if (message_size > thismessage_size_limit) break; \/* A line that is not syntactically correct for a header also marks the end of the headers. In this case, we leave next containing the first data line. This might actually be several lines because of the continuation logic applied above, but that doesn't matter. It turns out that smail, and presumably sendmail, accept leading lines of the form From ph10 Fri Jan 5 12:35 GMT 1996 in messages. The \"mail\" command on Solaris 2 sends such lines. I cannot find any documentation of this, but for compatibility it had better be accepted. Exim restricts it to the case of non-smtp messages, and treats it as an alternative to the -f command line option. Thus it is ignored except for trusted users or filter testing. Otherwise it is taken as the sender address, unless -f was used (sendmail compatibility). It further turns out that some UUCPs generate the From_line in a different format, e.g. From ph10 Fri, 7 Jan 97 14:00:00 GMT The regex for matching these things is now capable of recognizing both formats (including 2- and 4-digit years in the latter). In fact, the regex is now configurable, as is the expansion string to fish out the sender. Even further on it has been discovered that some broken clients send these lines in SMTP messages. There is now an option to ignore them from specified hosts or networks. Sigh. *\/ if (header_last == header_list && (!smtp_input || (sender_host_address != NULL && verify_check_host(&ignore_fromline_hosts) == OK) || (sender_host_address == NULL && ignore_fromline_local) ) && regex_match_and_setup(regex_From, next->text, 0, -1)) { if (!sender_address_forced) { uschar *uucp_sender = expand_string(uucp_from_sender); if (uucp_sender == NULL) { log_write(0, LOG_MAIN|LOG_PANIC, \"expansion of \\\"%s\\\" failed after matching \" \"\\\"From \\\" line: %s\", uucp_from_sender, expand_string_message); } else { int start, end, domain; uschar *errmess; uschar *newsender = parse_extract_address(uucp_sender, &errmess, &start, &end, &domain, TRUE); if (newsender != NULL) { if (domain == 0 && newsender[0] != 0) newsender = rewrite_address_qualify(newsender, FALSE); if (filter_test != FTEST_NONE || receive_check_set_sender(newsender)) { sender_address = newsender; if (trusted_caller || filter_test != FTEST_NONE) { authenticated_sender = NULL; originator_name = US\"\"; sender_local = FALSE; } if (filter_test != FTEST_NONE) printf(\"Sender taken from \\\"From \\\" line\\n\"); } } } } } \/* Not a leading \"From \" line. Check to see if it is a valid header line. Header names may contain any non-control characters except space and colon, amazingly. *\/ else { uschar *p = next->text; \/* If not a valid header line, break from the header reading loop, leaving next != NULL, indicating that it holds the first line of the body. *\/ if (isspace(*p)) break; while (mac_isgraph(*p) && *p != ':') p++; while (isspace(*p)) p++; if (*p != ':') { body_zerocount = had_zero; break; } \/* We have a valid header line. If there were any binary zeroes in the line, stomp on them here. *\/ if (had_zero > 0) for (p = next->text; p < next->text + ptr; p++) if (*p == 0) *p = '?'; \/* It is perfectly legal to have an empty continuation line at the end of a header, but it is confusing to humans looking at such messages, since it looks like a blank line. Reduce confusion by removing redundant white space at the end. We know that there is at least one printing character (the ':' tested for above) so there is no danger of running off the end. *\/ p = next->text + ptr - 2; for (;;) { while (*p == ' ' || *p == '\\t') p--; if (*p != '\\n') break; ptr = (p--) - next->text + 1; message_size -= next->slen - ptr; next->text[ptr] = 0; next->slen = ptr; } \/* Add the header to the chain *\/ next->type = htype_other; next->next = NULL; header_last->next = next; header_last = next; \/* Check the limit for individual line lengths. This comes after adding to the chain so that the failing line is reflected if a bounce is generated (for a local message). *\/ if (header_line_maxsize > 0 && next->slen > header_line_maxsize) { log_write(0, LOG_MAIN, \"overlong message header line received from \" \"%s (more than %d characters): message abandoned\", sender_host_unknown? sender_ident : sender_fullhost, header_line_maxsize); if (smtp_input) { smtp_reply = US\"552 A message header line is too long\"; receive_swallow_smtp(); goto TIDYUP; \/* Skip to end of function *\/ } else { give_local_error(ERRMESS_VLONGHDRLINE, string_sprintf(\"message header line longer than %d characters \" \"received: message not accepted\", header_line_maxsize), US\"\", error_rc, stdin, header_list->next); \/* Does not return *\/ } } \/* Note if any resent- fields exist. *\/ if (!resents_exist && strncmpic(next->text, US\"resent-\", 7) == 0) { resents_exist = TRUE; resent_prefix = US\"Resent-\"; } } \/* Reject CHUNKING messages that do not CRLF their first header line *\/ if (!first_line_ended_crlf && chunking_state > CHUNKING_OFFERED) { log_write(L_size_reject, LOG_MAIN|LOG_REJECT, \"rejected from <%s>%s%s%s%s: \" \"Non-CRLF-terminated header, under CHUNKING: message abandoned\", sender_address, sender_fullhost ? \" H=\" : \"\", sender_fullhost ? sender_fullhost : US\"\", sender_ident ? \" U=\" : \"\", sender_ident ? sender_ident : US\"\"); smtp_printf(\"552 Message header not CRLF terminated\\r\\n\", FALSE); bdat_flush_data(); smtp_reply = US\"\"; goto TIDYUP; \/* Skip to end of function *\/ } \/* The line has been handled. If we have hit EOF, break out of the loop, indicating no pending data line. *\/ if (ch == EOF) { next = NULL; break; } \/* Set up for the next header *\/ header_size = 256; next = store_get(sizeof(header_line)); next->text = store_get(header_size); ptr = 0; had_zero = 0; prevlines_length = 0; } \/* Continue, starting to read the next header *\/ \/* At this point, we have read all the headers into a data structure in main store. The first header is still the dummy placeholder for the Received: header we are going to generate a bit later on. If next != NULL, it contains the first data line - which terminated the headers before reaching a blank line (not the normal case). *\/ DEBUG(D_receive) { debug_printf(\">>Headers received:\\n\"); for (h = header_list->next; h; h = h->next) debug_printf(\"%s\", h->text); debug_printf(\"\\n\"); } \/* End of file on any SMTP connection is an error. If an incoming SMTP call is dropped immediately after valid headers, the next thing we will see is EOF. We must test for this specially, as further down the reading of the data is skipped if already at EOF. *\/ if (smtp_input && (receive_feof)()) { smtp_reply = handle_lost_connection(US\" (after header)\"); smtp_yield = FALSE; goto TIDYUP; \/* Skip to end of function *\/ } \/* If this is a filter test run and no headers were read, output a warning in case there is a mistake in the test message. *\/ if (filter_test != FTEST_NONE && header_list->next == NULL) printf(\"Warning: no message headers read\\n\"); \/* Scan the headers to identify them. Some are merely marked for later processing; some are dealt with here. *\/ for (h = header_list->next; h; h = h->next) { BOOL is_resent = strncmpic(h->text, US\"resent-\", 7) == 0; if (is_resent) contains_resent_headers = TRUE; switch (header_checkname(h, is_resent)) { case htype_bcc: h->type = htype_bcc; \/* Both Bcc: and Resent-Bcc: *\/ break; case htype_cc: h->type = htype_cc; \/* Both Cc: and Resent-Cc: *\/ break; \/* Record whether a Date: or Resent-Date: header exists, as appropriate. *\/ case htype_date: if (!resents_exist || is_resent) date_header_exists = TRUE; break; \/* Same comments as about Return-Path: below. *\/ case htype_delivery_date: if (delivery_date_remove) h->type = htype_old; break; \/* Same comments as about Return-Path: below. *\/ case htype_envelope_to: if (envelope_to_remove) h->type = htype_old; break; \/* Mark all \"From:\" headers so they get rewritten. Save the one that is to be used for Sender: checking. For Sendmail compatibility, if the \"From:\" header consists of just the login id of the user who called Exim, rewrite it with the gecos field first. Apply this rule to Resent-From: if there are resent- fields. *\/ case htype_from: h->type = htype_from; if (!resents_exist || is_resent) { from_header = h; if (!smtp_input) { int len; uschar *s = Ustrchr(h->text, ':') + 1; while (isspace(*s)) s++; len = h->slen - (s - h->text) - 1; if (Ustrlen(originator_login) == len && strncmpic(s, originator_login, len) == 0) { uschar *name = is_resent? US\"Resent-From\" : US\"From\"; header_add(htype_from, \"%s: %s <%s@%s>\\n\", name, originator_name, originator_login, qualify_domain_sender); from_header = header_last; h->type = htype_old; DEBUG(D_receive|D_rewrite) debug_printf(\"rewrote \\\"%s:\\\" header using gecos\\n\", name); } } } break; \/* Identify the Message-id: header for generating \"in-reply-to\" in the autoreply transport. For incoming logging, save any resent- value. In both cases, take just the first of any multiples. *\/ case htype_id: if (msgid_header == NULL && (!resents_exist || is_resent)) { msgid_header = h; h->type = htype_id; } break; \/* Flag all Received: headers *\/ case htype_received: h->type = htype_received; received_count++; break; \/* \"Reply-to:\" is just noted (there is no resent-reply-to field) *\/ case htype_reply_to: h->type = htype_reply_to; break; \/* The Return-path: header is supposed to be added to messages when they leave the SMTP system. We shouldn't receive messages that already contain Return-path. However, since Exim generates Return-path: on local delivery, resent messages may well contain it. We therefore provide an option (which defaults on) to remove any Return-path: headers on input. Removal actually means flagging as \"old\", which prevents the header being transmitted with the message. *\/ case htype_return_path: if (return_path_remove) h->type = htype_old; \/* If we are testing a mail filter file, use the value of the Return-Path: header to set up the return_path variable, which is not otherwise set. However, remove any <> that surround the address because the variable doesn't have these. *\/ if (filter_test != FTEST_NONE) { uschar *start = h->text + 12; uschar *end = start + Ustrlen(start); while (isspace(*start)) start++; while (end > start && isspace(end[-1])) end--; if (*start == '<' && end[-1] == '>') { start++; end--; } return_path = string_copyn(start, end - start); printf(\"Return-path taken from \\\"Return-path:\\\" header line\\n\"); } break; \/* If there is a \"Sender:\" header and the message is locally originated, and from an untrusted caller and suppress_local_fixups is not set, or if we are in submission mode for a remote message, mark it \"old\" so that it will not be transmitted with the message, unless active_local_sender_retain is set. (This can only be true if active_local_from_check is false.) If there are any resent- headers in the message, apply this rule to Resent-Sender: instead of Sender:. Messages with multiple resent- header sets cannot be tidily handled. (For this reason, at least one MUA - Pine - turns old resent- headers into X-resent- headers when resending, leaving just one set.) *\/ case htype_sender: h->type = ((!active_local_sender_retain && ( (sender_local && !trusted_caller && !suppress_local_fixups) || submission_mode ) ) && (!resents_exist||is_resent))? htype_old : htype_sender; break; \/* Remember the Subject: header for logging. There is no Resent-Subject *\/ case htype_subject: subject_header = h; break; \/* \"To:\" gets flagged, and the existence of a recipient header is noted, whether it's resent- or not. *\/ case htype_to: h->type = htype_to; \/**** to_or_cc_header_exists = TRUE; ****\/ break; } } \/* Extract recipients from the headers if that is required (the -t option). Note that this is documented as being done *before* any address rewriting takes place. There are two possibilities: (1) According to sendmail documentation for Solaris, IRIX, and HP-UX, any recipients already listed are to be REMOVED from the message. Smail 3 works like this. We need to build a non-recipients tree for that list, because in subsequent processing this data is held in a tree and that's what the spool_write_header() function expects. Make sure that non-recipient addresses are fully qualified and rewritten if necessary. (2) According to other sendmail documentation, -t ADDS extracted recipients to those in the command line arguments (and it is rumoured some other MTAs do this). Therefore, there is an option to make Exim behave this way. *** Notes on \"Resent-\" header lines *** The presence of resent-headers in the message makes -t horribly ambiguous. Experiments with sendmail showed that it uses recipients for all resent- headers, totally ignoring the concept of \"sets of resent- headers\" as described in RFC 2822 section 3.6.6. Sendmail also amalgamates them into a single set with all the addresses in one instance of each header. This seems to me not to be at all sensible. Before release 4.20, Exim 4 gave an error for -t if there were resent- headers in the message. However, after a discussion on the mailing list, I've learned that there are MUAs that use resent- headers with -t, and also that the stuff about sets of resent- headers and their ordering in RFC 2822 is generally ignored. An MUA that submits a message with -t and resent- header lines makes sure that only *its* resent- headers are present; previous ones are often renamed as X-resent- for example. Consequently, Exim has been changed so that, if any resent- header lines are present, the recipients are taken from all of the appropriate resent- lines, and not from the ordinary To:, Cc:, etc. *\/ if (extract_recip) { int rcount = 0; error_block **bnext = &bad_addresses; if (extract_addresses_remove_arguments) { while (recipients_count-- > 0) { uschar *s = rewrite_address(recipients_list[recipients_count].address, TRUE, TRUE, global_rewrite_rules, rewrite_existflags); tree_add_nonrecipient(s); } recipients_list = NULL; recipients_count = recipients_list_max = 0; } \/* Now scan the headers *\/ for (h = header_list->next; h; h = h->next) { if ((h->type == htype_to || h->type == htype_cc || h->type == htype_bcc) && (!contains_resent_headers || strncmpic(h->text, US\"resent-\", 7) == 0)) { uschar *s = Ustrchr(h->text, ':') + 1; while (isspace(*s)) s++; parse_allow_group = TRUE; \/* Allow address group syntax *\/ while (*s != 0) { uschar *ss = parse_find_address_end(s, FALSE); uschar *recipient, *errmess, *p, *pp; int start, end, domain; \/* Check on maximum *\/ if (recipients_max > 0 && ++rcount > recipients_max) { give_local_error(ERRMESS_TOOMANYRECIP, US\"too many recipients\", US\"message rejected: \", error_rc, stdin, NULL); \/* Does not return *\/ } \/* Make a copy of the address, and remove any internal newlines. These may be present as a result of continuations of the header line. The white space that follows the newline must not be removed - it is part of the header. *\/ pp = recipient = store_get(ss - s + 1); for (p = s; p < ss; p++) if (*p != '\\n') *pp++ = *p; *pp = 0; #ifdef SUPPORT_I18N { BOOL b = allow_utf8_domains; allow_utf8_domains = TRUE; #endif recipient = parse_extract_address(recipient, &errmess, &start, &end, &domain, FALSE); #ifdef SUPPORT_I18N if (string_is_utf8(recipient)) message_smtputf8 = TRUE; else allow_utf8_domains = b; } #endif \/* Keep a list of all the bad addresses so we can send a single error message at the end. However, an empty address is not an error; just ignore it. This can come from an empty group list like To: Recipients of list:; If there are no recipients at all, an error will occur later. *\/ if (recipient == NULL && Ustrcmp(errmess, \"empty address\") != 0) { int len = Ustrlen(s); error_block *b = store_get(sizeof(error_block)); while (len > 0 && isspace(s[len-1])) len--; b->next = NULL; b->text1 = string_printing(string_copyn(s, len)); b->text2 = errmess; *bnext = b; bnext = &(b->next); } \/* If the recipient is already in the nonrecipients tree, it must have appeared on the command line with the option extract_addresses_ remove_arguments set. Do not add it to the recipients, and keep a note that this has happened, in order to give a better error if there are no recipients left. *\/ else if (recipient != NULL) { if (tree_search(tree_nonrecipients, recipient) == NULL) receive_add_recipient(recipient, -1); else extracted_ignored = TRUE; } \/* Move on past this address *\/ s = ss + (*ss? 1:0); while (isspace(*s)) s++; } \/* Next address *\/ parse_allow_group = FALSE; \/* Reset group syntax flags *\/ parse_found_group = FALSE; \/* If this was the bcc: header, mark it \"old\", which means it will be kept on the spool, but not transmitted as part of the message. *\/ if (h->type == htype_bcc) h->type = htype_old; } \/* For appropriate header line *\/ } \/* For each header line *\/ } \/* Now build the unique message id. This has changed several times over the lifetime of Exim. This description was rewritten for Exim 4.14 (February 2003). Retaining all the history in the comment has become too unwieldy - read previous release sources if you want it. The message ID has 3 parts: tttttt-pppppp-ss. Each part is a number in base 62. The first part is the current time, in seconds. The second part is the current pid. Both are large enough to hold 32-bit numbers in base 62. The third part can hold a number in the range 0-3843. It used to be a computed sequence number, but is now the fractional component of the current time in units of 1\/2000 of a second (i.e. a value in the range 0-1999). After a message has been received, Exim ensures that the timer has ticked at the appropriate level before proceeding, to avoid duplication if the pid happened to be re-used within the same time period. It seems likely that most messages will take at least half a millisecond to be received, so no delay will normally be necessary. At least for some time... There is a modification when localhost_number is set. Formerly this was allowed to be as large as 255. Now it is restricted to the range 0-16, and the final component of the message id becomes (localhost_number * 200) + fractional time in units of 1\/200 of a second (i.e. a value in the range 0-3399). Some not-really-Unix operating systems use case-insensitive file names (Darwin, Cygwin). For these, we have to use base 36 instead of base 62. Luckily, this still allows the tttttt field to hold a large enough number to last for some more decades, and the final two-digit field can hold numbers up to 1295, which is enough for milliseconds (instead of 1\/2000 of a second). However, the pppppp field cannot hold a 32-bit pid, but it can hold a 31-bit pid, so it is probably safe because pids have to be positive. The localhost_number is restricted to 0-10 for these hosts, and when it is set, the final field becomes (localhost_number * 100) + fractional time in centiseconds. Note that string_base62() returns its data in a static storage block, so it must be copied before calling string_base62() again. It always returns exactly 6 characters. There doesn't seem to be anything in the RFC which requires a message id to start with a letter, but Smail was changed to ensure this. The external form of the message id (as supplied by string expansion) therefore starts with an additional leading 'E'. The spool file names do not include this leading letter and it is not used internally. NOTE: If ever the format of message ids is changed, the regular expression for checking that a string is in this format must be updated in a corresponding way. It appears in the initializing code in exim.c. The macro MESSAGE_ID_LENGTH must also be changed to reflect the correct string length. The queue-sort code needs to know the layout. Then, of course, other programs that rely on the message id format will need updating too. *\/ Ustrncpy(message_id, string_base62((long int)(message_id_tv.tv_sec)), 6); message_id[6] = '-'; Ustrncpy(message_id + 7, string_base62((long int)getpid()), 6); \/* Deal with the case where the host number is set. The value of the number was checked when it was read, to ensure it isn't too big. The timing granularity is left in id_resolution so that an appropriate wait can be done after receiving the message, if necessary (we hope it won't be). *\/ if (host_number_string != NULL) { id_resolution = (BASE_62 == 62)? 5000 : 10000; sprintf(CS(message_id + MESSAGE_ID_LENGTH - 3), \"-%2s\", string_base62((long int)( host_number * (1000000\/id_resolution) + message_id_tv.tv_usec\/id_resolution)) + 4); } \/* Host number not set: final field is just the fractional time at an appropriate resolution. *\/ else { id_resolution = (BASE_62 == 62)? 500 : 1000; sprintf(CS(message_id + MESSAGE_ID_LENGTH - 3), \"-%2s\", string_base62((long int)(message_id_tv.tv_usec\/id_resolution)) + 4); } \/* Add the current message id onto the current process info string if it will fit. *\/ (void)string_format(process_info + process_info_len, PROCESS_INFO_SIZE - process_info_len, \" id=%s\", message_id); \/* If we are using multiple input directories, set up the one for this message to be the least significant base-62 digit of the time of arrival. Otherwise ensure that it is an empty string. *\/ message_subdir[0] = split_spool_directory ? message_id[5] : 0; \/* Now that we have the message-id, if there is no message-id: header, generate one, but only for local (without suppress_local_fixups) or submission mode messages. This can be user-configured if required, but we had better flatten any illegal characters therein. *\/ if (msgid_header == NULL && ((sender_host_address == NULL && !suppress_local_fixups) || submission_mode)) { uschar *p; uschar *id_text = US\"\"; uschar *id_domain = primary_hostname; \/* Permit only letters, digits, dots, and hyphens in the domain *\/ if (message_id_domain != NULL) { uschar *new_id_domain = expand_string(message_id_domain); if (new_id_domain == NULL) { if (!expand_string_forcedfail) log_write(0, LOG_MAIN|LOG_PANIC, \"expansion of \\\"%s\\\" (message_id_header_domain) \" \"failed: %s\", message_id_domain, expand_string_message); } else if (*new_id_domain != 0) { id_domain = new_id_domain; for (p = id_domain; *p != 0; p++) if (!isalnum(*p) && *p != '.') *p = '-'; \/* No need to test '-' ! *\/ } } \/* Permit all characters except controls and RFC 2822 specials in the additional text part. *\/ if (message_id_text != NULL) { uschar *new_id_text = expand_string(message_id_text); if (new_id_text == NULL) { if (!expand_string_forcedfail) log_write(0, LOG_MAIN|LOG_PANIC, \"expansion of \\\"%s\\\" (message_id_header_text) \" \"failed: %s\", message_id_text, expand_string_message); } else if (*new_id_text != 0) { id_text = new_id_text; for (p = id_text; *p != 0; p++) if (mac_iscntrl_or_special(*p)) *p = '-'; } } \/* Add the header line * Resent-* headers are prepended, per RFC 5322 3.6.6. Non-Resent-* are * appended, to preserve classical expectations of header ordering. *\/ header_add_at_position(!resents_exist, NULL, FALSE, htype_id, \"%sMessage-Id: <%s%s%s@%s>\\n\", resent_prefix, message_id_external, (*id_text == 0)? \"\" : \".\", id_text, id_domain); } \/* If we are to log recipients, keep a copy of the raw ones before any possible rewriting. Must copy the count, because later ACLs and the local_scan() function may mess with the real recipients. *\/ if (LOGGING(received_recipients)) { raw_recipients = store_get(recipients_count * sizeof(uschar *)); for (i = 0; i < recipients_count; i++) raw_recipients[i] = string_copy(recipients_list[i].address); raw_recipients_count = recipients_count; } \/* Ensure the recipients list is fully qualified and rewritten. Unqualified recipients will get here only if the conditions were right (allow_unqualified_ recipient is TRUE). *\/ for (i = 0; i < recipients_count; i++) recipients_list[i].address = rewrite_address(recipients_list[i].address, TRUE, TRUE, global_rewrite_rules, rewrite_existflags); \/* If there is no From: header, generate one for local (without suppress_local_fixups) or submission_mode messages. If there is no sender address, but the sender is local or this is a local delivery error, use the originator login. This shouldn't happen for genuine bounces, but might happen for autoreplies. The addition of From: must be done *before* checking for the possible addition of a Sender: header, because untrusted_set_sender allows an untrusted user to set anything in the envelope (which might then get info From:) but we still want to ensure a valid Sender: if it is required. *\/ if (from_header == NULL && ((sender_host_address == NULL && !suppress_local_fixups) || submission_mode)) { uschar *oname = US\"\"; \/* Use the originator_name if this is a locally submitted message and the caller is not trusted. For trusted callers, use it only if -F was used to force its value or if we have a non-SMTP message for which -f was not used to set the sender. *\/ if (sender_host_address == NULL) { if (!trusted_caller || sender_name_forced || (!smtp_input && !sender_address_forced)) oname = originator_name; } \/* For non-locally submitted messages, the only time we use the originator name is when it was forced by the \/name= option on control=submission. *\/ else { if (submission_name != NULL) oname = submission_name; } \/* Envelope sender is empty *\/ if (sender_address[0] == 0) { uschar *fromstart, *fromend; fromstart = string_sprintf(\"%sFrom: %s%s\", resent_prefix, oname, (oname[0] == 0)? \"\" : \" <\"); fromend = (oname[0] == 0)? US\"\" : US\">\"; if (sender_local || local_error_message) { header_add(htype_from, \"%s%s@%s%s\\n\", fromstart, local_part_quote(originator_login), qualify_domain_sender, fromend); } else if (submission_mode && authenticated_id != NULL) { if (submission_domain == NULL) { header_add(htype_from, \"%s%s@%s%s\\n\", fromstart, local_part_quote(authenticated_id), qualify_domain_sender, fromend); } else if (submission_domain[0] == 0) \/* empty => whole address set *\/ { header_add(htype_from, \"%s%s%s\\n\", fromstart, authenticated_id, fromend); } else { header_add(htype_from, \"%s%s@%s%s\\n\", fromstart, local_part_quote(authenticated_id), submission_domain, fromend); } from_header = header_last; \/* To get it checked for Sender: *\/ } } \/* There is a non-null envelope sender. Build the header using the original sender address, before any rewriting that might have been done while verifying it. *\/ else { header_add(htype_from, \"%sFrom: %s%s%s%s\\n\", resent_prefix, oname, (oname[0] == 0)? \"\" : \" <\", (sender_address_unrewritten == NULL)? sender_address : sender_address_unrewritten, (oname[0] == 0)? \"\" : \">\"); from_header = header_last; \/* To get it checked for Sender: *\/ } } \/* If the sender is local (without suppress_local_fixups), or if we are in submission mode and there is an authenticated_id, check that an existing From: is correct, and if not, generate a Sender: header, unless disabled. Any previously-existing Sender: header was removed above. Note that sender_local, as well as being TRUE if the caller of exim is not trusted, is also true if a trusted caller did not supply a -f argument for non-smtp input. To allow trusted callers to forge From: without supplying -f, we have to test explicitly here. If the From: header contains more than one address, then the call to parse_extract_address fails, and a Sender: header is inserted, as required. *\/ if (from_header != NULL && (active_local_from_check && ((sender_local && !trusted_caller && !suppress_local_fixups) || (submission_mode && authenticated_id != NULL)) )) { BOOL make_sender = TRUE; int start, end, domain; uschar *errmess; uschar *from_address = parse_extract_address(Ustrchr(from_header->text, ':') + 1, &errmess, &start, &end, &domain, FALSE); uschar *generated_sender_address; if (submission_mode) { if (submission_domain == NULL) { generated_sender_address = string_sprintf(\"%s@%s\", local_part_quote(authenticated_id), qualify_domain_sender); } else if (submission_domain[0] == 0) \/* empty => full address *\/ { generated_sender_address = string_sprintf(\"%s\", authenticated_id); } else { generated_sender_address = string_sprintf(\"%s@%s\", local_part_quote(authenticated_id), submission_domain); } } else generated_sender_address = string_sprintf(\"%s@%s\", local_part_quote(originator_login), qualify_domain_sender); \/* Remove permitted prefixes and suffixes from the local part of the From: address before doing the comparison with the generated sender. *\/ if (from_address != NULL) { int slen; uschar *at = (domain == 0)? NULL : from_address + domain - 1; if (at != NULL) *at = 0; from_address += route_check_prefix(from_address, local_from_prefix); slen = route_check_suffix(from_address, local_from_suffix); if (slen > 0) { memmove(from_address+slen, from_address, Ustrlen(from_address)-slen); from_address += slen; } if (at != NULL) *at = '@'; if (strcmpic(generated_sender_address, from_address) == 0 || (domain == 0 && strcmpic(from_address, originator_login) == 0)) make_sender = FALSE; } \/* We have to cause the Sender header to be rewritten if there are appropriate rewriting rules. *\/ if (make_sender) { if (submission_mode && submission_name == NULL) header_add(htype_sender, \"%sSender: %s\\n\", resent_prefix, generated_sender_address); else header_add(htype_sender, \"%sSender: %s <%s>\\n\", resent_prefix, submission_mode? submission_name : originator_name, generated_sender_address); } \/* Ensure that a non-null envelope sender address corresponds to the submission mode sender address. *\/ if (submission_mode && sender_address[0] != 0) { if (sender_address_unrewritten == NULL) sender_address_unrewritten = sender_address; sender_address = generated_sender_address; if (Ustrcmp(sender_address_unrewritten, generated_sender_address) != 0) log_write(L_address_rewrite, LOG_MAIN, \"\\\"%s\\\" from env-from rewritten as \\\"%s\\\" by submission mode\", sender_address_unrewritten, generated_sender_address); } } \/* If there are any rewriting rules, apply them to the sender address, unless it has already been rewritten as part of verification for SMTP input. *\/ if (global_rewrite_rules != NULL && sender_address_unrewritten == NULL && sender_address[0] != 0) { sender_address = rewrite_address(sender_address, FALSE, TRUE, global_rewrite_rules, rewrite_existflags); DEBUG(D_receive|D_rewrite) debug_printf(\"rewritten sender = %s\\n\", sender_address); } \/* The headers must be run through rewrite_header(), because it ensures that addresses are fully qualified, as well as applying any rewriting rules that may exist. Qualification of header addresses in a message from a remote host happens only if the host is in sender_unqualified_hosts or recipient_unqualified hosts, as appropriate. For local messages, qualification always happens, unless -bnq is used to explicitly suppress it. No rewriting is done for an unqualified address that is left untouched. We start at the second header, skipping our own Received:. This rewriting is documented as happening *after* recipient addresses are taken from the headers by the -t command line option. An added Sender: gets rewritten here. *\/ for (h = header_list->next; h; h = h->next) { header_line *newh = rewrite_header(h, NULL, NULL, global_rewrite_rules, rewrite_existflags, TRUE); if (newh) h = newh; } \/* An RFC 822 (sic) message is not legal unless it has at least one of \"to\", \"cc\", or \"bcc\". Note that although the minimal examples in RFC 822 show just \"to\" or \"bcc\", the full syntax spec allows \"cc\" as well. If any resent- header exists, this applies to the set of resent- headers rather than the normal set. The requirement for a recipient header has been removed in RFC 2822. At this point in the code, earlier versions of Exim added a To: header for locally submitted messages, and an empty Bcc: header for others. In the light of the changes in RFC 2822, this was dropped in November 2003. *\/ \/* If there is no date header, generate one if the message originates locally (i.e. not over TCP\/IP) and suppress_local_fixups is not set, or if the submission mode flag is set. Messages without Date: are not valid, but it seems to be more confusing if Exim adds one to all remotely-originated messages. As per Message-Id, we prepend if resending, else append. *\/ if (!date_header_exists && ((sender_host_address == NULL && !suppress_local_fixups) || submission_mode)) header_add_at_position(!resents_exist, NULL, FALSE, htype_other, \"%sDate: %s\\n\", resent_prefix, tod_stamp(tod_full)); search_tidyup(); \/* Free any cached resources *\/ \/* Show the complete set of headers if debugging. Note that the first one (the new Received:) has not yet been set. *\/ DEBUG(D_receive) { debug_printf(\">>Headers after rewriting and local additions:\\n\"); for (h = header_list->next; h != NULL; h = h->next) debug_printf(\"%c %s\", h->type, h->text); debug_printf(\"\\n\"); } \/* The headers are now complete in store. If we are running in filter testing mode, that is all this function does. Return TRUE if the message ended with a dot. *\/ if (filter_test != FTEST_NONE) { process_info[process_info_len] = 0; return message_ended == END_DOT; } \/*XXX CHUNKING: need to cancel cutthrough under BDAT, for now. In future, think more if it could be handled. Cannot do onward CHUNKING unless inbound is, but inbound chunking ought to be ok with outbound plain. Could we do onward CHUNKING given inbound CHUNKING? *\/ if (chunking_state > CHUNKING_OFFERED) cancel_cutthrough_connection(FALSE, US\"chunking active\"); \/* Cutthrough delivery: We have to create the Received header now rather than at the end of reception, so the timestamp behaviour is a change to the normal case. Having created it, send the headers to the destination. *\/ if (cutthrough.fd >= 0 && cutthrough.delivery) { if (received_count > received_headers_max) { cancel_cutthrough_connection(TRUE, US\"too many headers\"); if (smtp_input) receive_swallow_smtp(); \/* Swallow incoming SMTP *\/ log_write(0, LOG_MAIN|LOG_REJECT, \"rejected from <%s>%s%s%s%s: \" \"Too many \\\"Received\\\" headers\", sender_address, sender_fullhost ? \"H=\" : \"\", sender_fullhost ? sender_fullhost : US\"\", sender_ident ? \"U=\" : \"\", sender_ident ? sender_ident : US\"\"); message_id[0] = 0; \/* Indicate no message accepted *\/ smtp_reply = US\"550 Too many \\\"Received\\\" headers - suspected mail loop\"; goto TIDYUP; \/* Skip to end of function *\/ } received_header_gen(); add_acl_headers(ACL_WHERE_RCPT, US\"MAIL or RCPT\"); (void) cutthrough_headers_send(); } \/* Open a new spool file for the data portion of the message. We need to access it both via a file descriptor and a stream. Try to make the directory if it isn't there. *\/ spool_name = spool_fname(US\"input\", message_subdir, message_id, US\"-D\"); DEBUG(D_receive) debug_printf(\"Data file name: %s\\n\", spool_name); if ((data_fd = Uopen(spool_name, O_RDWR|O_CREAT|O_EXCL, SPOOL_MODE)) < 0) { if (errno == ENOENT) { (void) directory_make(spool_directory, spool_sname(US\"input\", message_subdir), INPUT_DIRECTORY_MODE, TRUE); data_fd = Uopen(spool_name, O_RDWR|O_CREAT|O_EXCL, SPOOL_MODE); } if (data_fd < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Failed to create spool file %s: %s\", spool_name, strerror(errno)); } \/* Make sure the file's group is the Exim gid, and double-check the mode because the group setting doesn't always get set automatically. *\/ if (fchown(data_fd, exim_uid, exim_gid)) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Failed setting ownership on spool file %s: %s\", spool_name, strerror(errno)); (void)fchmod(data_fd, SPOOL_MODE); \/* We now have data file open. Build a stream for it and lock it. We lock only the first line of the file (containing the message ID) because otherwise there are problems when Exim is run under Cygwin (I'm told). See comments in spool_in.c, where the same locking is done. *\/ data_file = fdopen(data_fd, \"w+\"); lock_data.l_type = F_WRLCK; lock_data.l_whence = SEEK_SET; lock_data.l_start = 0; lock_data.l_len = SPOOL_DATA_START_OFFSET; if (fcntl(data_fd, F_SETLK, &lock_data) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Cannot lock %s (%d): %s\", spool_name, errno, strerror(errno)); \/* We have an open, locked data file. Write the message id to it to make it self-identifying. Then read the remainder of the input of this message and write it to the data file. If the variable next != NULL, it contains the first data line (which was read as a header but then turned out not to have the right format); write it (remembering that it might contain binary zeros). The result of fwrite() isn't inspected; instead we call ferror() below. *\/ fprintf(data_file, \"%s-D\\n\", message_id); if (next != NULL) { uschar *s = next->text; int len = next->slen; len = fwrite(s, 1, len, data_file); len = len; \/* compiler quietening *\/ body_linecount++; \/* Assumes only 1 line *\/ } \/* Note that we might already be at end of file, or the logical end of file (indicated by '.'), or might have encountered an error while writing the message id or \"next\" line. *\/ if (!ferror(data_file) && !(receive_feof)() && message_ended != END_DOT) { if (smtp_input) { message_ended = chunking_state <= CHUNKING_OFFERED ? read_message_data_smtp(data_file) : spool_wireformat ? read_message_bdat_smtp_wire(data_file) : read_message_bdat_smtp(data_file); receive_linecount++; \/* The terminating \".\" line *\/ } else message_ended = read_message_data(data_file); receive_linecount += body_linecount; \/* For BSMTP errors mainly *\/ message_linecount += body_linecount; switch (message_ended) { \/* Handle premature termination of SMTP *\/ case END_EOF: if (smtp_input) { Uunlink(spool_name); \/* Lose data file when closed *\/ cancel_cutthrough_connection(TRUE, US\"sender closed connection\"); message_id[0] = 0; \/* Indicate no message accepted *\/ smtp_reply = handle_lost_connection(US\"\"); smtp_yield = FALSE; goto TIDYUP; \/* Skip to end of function *\/ } break; \/* Handle message that is too big. Don't use host_or_ident() in the log message; we want to see the ident value even for non-remote messages. *\/ case END_SIZE: Uunlink(spool_name); \/* Lose the data file when closed *\/ cancel_cutthrough_connection(TRUE, US\"mail too big\"); if (smtp_input) receive_swallow_smtp(); \/* Swallow incoming SMTP *\/ log_write(L_size_reject, LOG_MAIN|LOG_REJECT, \"rejected from <%s>%s%s%s%s: \" \"message too big: read=%d max=%d\", sender_address, (sender_fullhost == NULL)? \"\" : \" H=\", (sender_fullhost == NULL)? US\"\" : sender_fullhost, (sender_ident == NULL)? \"\" : \" U=\", (sender_ident == NULL)? US\"\" : sender_ident, message_size, thismessage_size_limit); if (smtp_input) { smtp_reply = US\"552 Message size exceeds maximum permitted\"; message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_TOOBIG, string_sprintf(\"message too big (max=%d)\", thismessage_size_limit), US\"message rejected: \", error_rc, data_file, header_list); \/* Does not return *\/ } break; \/* Handle bad BDAT protocol sequence *\/ case END_PROTOCOL: Uunlink(spool_name); \/* Lose the data file when closed *\/ cancel_cutthrough_connection(TRUE, US\"sender protocol error\"); smtp_reply = US\"\"; \/* Response already sent *\/ message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } } \/* Restore the standard SIGALRM handler for any subsequent processing. (For example, there may be some expansion in an ACL that uses a timer.) *\/ os_non_restarting_signal(SIGALRM, sigalrm_handler); \/* The message body has now been read into the data file. Call fflush() to empty the buffers in C, and then call fsync() to get the data written out onto the disk, as fflush() doesn't do this (or at least, it isn't documented as having to do this). If there was an I\/O error on either input or output, attempt to send an error message, and unlink the spool file. For non-SMTP input we can then give up. Note that for SMTP input we must swallow the remainder of the input in cases of output errors, since the far end doesn't expect to see anything until the terminating dot line is sent. *\/ if (fflush(data_file) == EOF || ferror(data_file) || EXIMfsync(fileno(data_file)) < 0 || (receive_ferror)()) { uschar *msg_errno = US strerror(errno); BOOL input_error = (receive_ferror)() != 0; uschar *msg = string_sprintf(\"%s error (%s) while receiving message from %s\", input_error? \"Input read\" : \"Spool write\", msg_errno, (sender_fullhost != NULL)? sender_fullhost : sender_ident); log_write(0, LOG_MAIN, \"Message abandoned: %s\", msg); Uunlink(spool_name); \/* Lose the data file *\/ cancel_cutthrough_connection(TRUE, US\"error writing spoolfile\"); if (smtp_input) { if (input_error) smtp_reply = US\"451 Error while reading input data\"; else { smtp_reply = US\"451 Error while writing spool file\"; receive_swallow_smtp(); } message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_IOERR, msg, US\"\", error_rc, data_file, header_list); \/* Does not return *\/ } } \/* No I\/O errors were encountered while writing the data file. *\/ DEBUG(D_receive) debug_printf(\"Data file written for message %s\\n\", message_id); \/* If there were any bad addresses extracted by -t, or there were no recipients left after -t, send a message to the sender of this message, or write it to stderr if the error handling option is set that way. Note that there may legitimately be no recipients for an SMTP message if they have all been removed by \"discard\". We need to rewind the data file in order to read it. In the case of no recipients or stderr error writing, throw the data file away afterwards, and exit. (This can't be SMTP, which always ensures there's at least one syntactically good recipient address.) *\/ if (extract_recip && (bad_addresses != NULL || recipients_count == 0)) { DEBUG(D_receive) { if (recipients_count == 0) debug_printf(\"*** No recipients\\n\"); if (bad_addresses != NULL) { error_block *eblock = bad_addresses; debug_printf(\"*** Bad address(es)\\n\"); while (eblock != NULL) { debug_printf(\" %s: %s\\n\", eblock->text1, eblock->text2); eblock = eblock->next; } } } fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); \/* If configured to send errors to the sender, but this fails, force a failure error code. We use a special one for no recipients so that it can be detected by the autoreply transport. Otherwise error_rc is set to errors_sender_rc, which is EXIT_FAILURE unless -oee was given, in which case it is EXIT_SUCCESS. *\/ if (error_handling == ERRORS_SENDER) { if (!moan_to_sender( (bad_addresses == NULL)? (extracted_ignored? ERRMESS_IGADDRESS : ERRMESS_NOADDRESS) : (recipients_list == NULL)? ERRMESS_BADNOADDRESS : ERRMESS_BADADDRESS, bad_addresses, header_list, data_file, FALSE)) error_rc = (bad_addresses == NULL)? EXIT_NORECIPIENTS : EXIT_FAILURE; } else { if (bad_addresses == NULL) { if (extracted_ignored) fprintf(stderr, \"exim: all -t recipients overridden by command line\\n\"); else fprintf(stderr, \"exim: no recipients in message\\n\"); } else { fprintf(stderr, \"exim: invalid address%s\", (bad_addresses->next == NULL)? \":\" : \"es:\\n\"); while (bad_addresses != NULL) { fprintf(stderr, \" %s: %s\\n\", bad_addresses->text1, bad_addresses->text2); bad_addresses = bad_addresses->next; } } } if (recipients_count == 0 || error_handling == ERRORS_STDERR) { Uunlink(spool_name); (void)fclose(data_file); exim_exit(error_rc, US\"receiving\"); } } \/* Data file successfully written. Generate text for the Received: header by expanding the configured string, and adding a timestamp. By leaving this operation till now, we ensure that the timestamp is the time that message reception was completed. However, this is deliberately done before calling the data ACL and local_scan(). This Received: header may therefore be inspected by the data ACL and by code in the local_scan() function. When they have run, we update the timestamp to be the final time of reception. If there is just one recipient, set up its value in the $received_for variable for use when we generate the Received: header. Note: the checking for too many Received: headers is handled by the delivery code. *\/ \/*XXX eventually add excess Received: check for cutthrough case back when classifying them *\/ if (received_header->text == NULL) \/* Non-cutthrough case *\/ { received_header_gen(); \/* Set the value of message_body_size for the DATA ACL and for local_scan() *\/ message_body_size = (fstat(data_fd, &statbuf) == 0)? statbuf.st_size - SPOOL_DATA_START_OFFSET : -1; \/* If an ACL from any RCPT commands set up any warning headers to add, do so now, before running the DATA ACL. *\/ add_acl_headers(ACL_WHERE_RCPT, US\"MAIL or RCPT\"); } else message_body_size = (fstat(data_fd, &statbuf) == 0)? statbuf.st_size - SPOOL_DATA_START_OFFSET : -1; \/* If an ACL is specified for checking things at this stage of reception of a message, run it, unless all the recipients were removed by \"discard\" in earlier ACLs. That is the only case in which recipients_count can be zero at this stage. Set deliver_datafile to point to the data file so that $message_body and $message_body_end can be extracted if needed. Allow $recipients in expansions. *\/ deliver_datafile = data_fd; user_msg = NULL; enable_dollar_recipients = TRUE; if (recipients_count == 0) blackholed_by = recipients_discarded ? US\"MAIL ACL\" : US\"RCPT ACL\"; else { \/* Handle interactive SMTP messages *\/ if (smtp_input && !smtp_batched_input) { #ifndef DISABLE_DKIM if (!dkim_disable_verify) { \/* Finish verification *\/ dkim_exim_verify_finish(); \/* Check if we must run the DKIM ACL *\/ if (acl_smtp_dkim && dkim_verify_signers && *dkim_verify_signers) { uschar * dkim_verify_signers_expanded = expand_string(dkim_verify_signers); gstring * results = NULL; int signer_sep = 0; const uschar * ptr; uschar * item; gstring * seen_items = NULL; int old_pool = store_pool; store_pool = POOL_PERM; \/* Allow created variables to live to data ACL *\/ if (!(ptr = dkim_verify_signers_expanded)) log_write(0, LOG_MAIN|LOG_PANIC, \"expansion of dkim_verify_signers option failed: %s\", expand_string_message); \/* Default to OK when no items are present *\/ rc = OK; while ((item = string_nextinlist(&ptr, &signer_sep, NULL, 0))) { \/* Prevent running ACL for an empty item *\/ if (!item || !*item) continue; \/* Only run ACL once for each domain or identity, no matter how often it appears in the expanded list. *\/ if (seen_items) { uschar * seen_item; const uschar * seen_items_list = string_from_gstring(seen_items); int seen_sep = ':'; BOOL seen_this_item = FALSE; while ((seen_item = string_nextinlist(&seen_items_list, &seen_sep, NULL, 0))) if (Ustrcmp(seen_item,item) == 0) { seen_this_item = TRUE; break; } if (seen_this_item) { DEBUG(D_receive) debug_printf(\"acl_smtp_dkim: skipping signer %s, \" \"already seen\\n\", item); continue; } seen_items = string_catn(seen_items, \":\", 1); } seen_items = string_cat(seen_items, item); rc = dkim_exim_acl_run(item, &results, &user_msg, &log_msg); if (rc != OK) { DEBUG(D_receive) debug_printf(\"acl_smtp_dkim: acl_check returned %d on %s, \" \"skipping remaining items\\n\", rc, item); cancel_cutthrough_connection(TRUE, US\"dkim acl not ok\"); break; } } dkim_verify_status = string_from_gstring(results); store_pool = old_pool; add_acl_headers(ACL_WHERE_DKIM, US\"DKIM\"); if (rc == DISCARD) { recipients_count = 0; blackholed_by = US\"DKIM ACL\"; if (log_msg) blackhole_log_msg = string_sprintf(\": %s\", log_msg); } else if (rc != OK) { Uunlink(spool_name); if (smtp_handle_acl_fail(ACL_WHERE_DKIM, rc, user_msg, log_msg) != 0) smtp_yield = FALSE; \/* No more messages after dropped connection *\/ smtp_reply = US\"\"; \/* Indicate reply already sent *\/ message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } } else dkim_exim_verify_log_all(); } #endif \/* DISABLE_DKIM *\/ #ifdef WITH_CONTENT_SCAN if (recipients_count > 0 && acl_smtp_mime != NULL && !run_mime_acl(acl_smtp_mime, &smtp_yield, &smtp_reply, &blackholed_by)) goto TIDYUP; #endif \/* WITH_CONTENT_SCAN *\/ #ifdef EXPERIMENTAL_DMARC dmarc_up = dmarc_store_data(from_header); #endif \/* EXPERIMENTAL_DMARC *\/ #ifndef DISABLE_PRDR if (prdr_requested && recipients_count > 1 && acl_smtp_data_prdr) { unsigned int c; int all_pass = OK; int all_fail = FAIL; smtp_printf(\"353 PRDR content analysis beginning\\r\\n\", TRUE); \/* Loop through recipients, responses must be in same order received *\/ for (c = 0; recipients_count > c; c++) { uschar * addr= recipients_list[c].address; uschar * msg= US\"PRDR R=<%s> %s\"; uschar * code; DEBUG(D_receive) debug_printf(\"PRDR processing recipient %s (%d of %d)\\n\", addr, c+1, recipients_count); rc = acl_check(ACL_WHERE_PRDR, addr, acl_smtp_data_prdr, &user_msg, &log_msg); \/* If any recipient rejected content, indicate it in final message *\/ all_pass |= rc; \/* If all recipients rejected, indicate in final message *\/ all_fail &= rc; switch (rc) { case OK: case DISCARD: code = US\"250\"; break; case DEFER: code = US\"450\"; break; default: code = US\"550\"; break; } if (user_msg != NULL) smtp_user_msg(code, user_msg); else { switch (rc) { case OK: case DISCARD: msg = string_sprintf(CS msg, addr, \"acceptance\"); break; case DEFER: msg = string_sprintf(CS msg, addr, \"temporary refusal\"); break; default: msg = string_sprintf(CS msg, addr, \"refusal\"); break; } smtp_user_msg(code, msg); } if (log_msg) log_write(0, LOG_MAIN, \"PRDR %s %s\", addr, log_msg); else if (user_msg) log_write(0, LOG_MAIN, \"PRDR %s %s\", addr, user_msg); else log_write(0, LOG_MAIN, \"%s\", CS msg); if (rc != OK) { receive_remove_recipient(addr); c--; } } \/* Set up final message, used if data acl gives OK *\/ smtp_reply = string_sprintf(\"%s id=%s message %s\", all_fail == FAIL ? US\"550\" : US\"250\", message_id, all_fail == FAIL ? US\"rejected for all recipients\" : all_pass == OK ? US\"accepted\" : US\"accepted for some recipients\"); if (recipients_count == 0) { message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; } } else prdr_requested = FALSE; #endif \/* !DISABLE_PRDR *\/ \/* Check the recipients count again, as the MIME ACL might have changed them. *\/ if (acl_smtp_data != NULL && recipients_count > 0) { rc = acl_check(ACL_WHERE_DATA, NULL, acl_smtp_data, &user_msg, &log_msg); add_acl_headers(ACL_WHERE_DATA, US\"DATA\"); if (rc == DISCARD) { recipients_count = 0; blackholed_by = US\"DATA ACL\"; if (log_msg) blackhole_log_msg = string_sprintf(\": %s\", log_msg); cancel_cutthrough_connection(TRUE, US\"data acl discard\"); } else if (rc != OK) { Uunlink(spool_name); cancel_cutthrough_connection(TRUE, US\"data acl not ok\"); #ifdef WITH_CONTENT_SCAN unspool_mbox(); #endif #ifdef EXPERIMENTAL_DCC dcc_ok = 0; #endif if (smtp_handle_acl_fail(ACL_WHERE_DATA, rc, user_msg, log_msg) != 0) smtp_yield = FALSE; \/* No more messages after dropped connection *\/ smtp_reply = US\"\"; \/* Indicate reply already sent *\/ message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } } } \/* Handle non-SMTP and batch SMTP (i.e. non-interactive) messages. Note that we cannot take different actions for permanent and temporary rejections. *\/ else { #ifdef WITH_CONTENT_SCAN if (acl_not_smtp_mime != NULL && !run_mime_acl(acl_not_smtp_mime, &smtp_yield, &smtp_reply, &blackholed_by)) goto TIDYUP; #endif \/* WITH_CONTENT_SCAN *\/ if (acl_not_smtp != NULL) { uschar *user_msg, *log_msg; rc = acl_check(ACL_WHERE_NOTSMTP, NULL, acl_not_smtp, &user_msg, &log_msg); if (rc == DISCARD) { recipients_count = 0; blackholed_by = US\"non-SMTP ACL\"; if (log_msg != NULL) blackhole_log_msg = string_sprintf(\": %s\", log_msg); } else if (rc != OK) { Uunlink(spool_name); #ifdef WITH_CONTENT_SCAN unspool_mbox(); #endif #ifdef EXPERIMENTAL_DCC dcc_ok = 0; #endif \/* The ACL can specify where rejections are to be logged, possibly nowhere. The default is main and reject logs. *\/ if (log_reject_target != 0) log_write(0, log_reject_target, \"F=<%s> rejected by non-SMTP ACL: %s\", sender_address, log_msg); if (user_msg == NULL) user_msg = US\"local configuration problem\"; if (smtp_batched_input) { moan_smtp_batch(NULL, \"%d %s\", 550, user_msg); \/* Does not return *\/ } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_LOCAL_ACL, user_msg, US\"message rejected by non-SMTP ACL: \", error_rc, data_file, header_list); \/* Does not return *\/ } } add_acl_headers(ACL_WHERE_NOTSMTP, US\"non-SMTP\"); } } \/* The applicable ACLs have been run *\/ if (deliver_freeze) frozen_by = US\"ACL\"; \/* for later logging *\/ if (queue_only_policy) queued_by = US\"ACL\"; } #ifdef WITH_CONTENT_SCAN unspool_mbox(); #endif #ifdef EXPERIMENTAL_DCC dcc_ok = 0; #endif \/* The final check on the message is to run the scan_local() function. The version supplied with Exim always accepts, but this is a hook for sysadmins to supply their own checking code. The local_scan() function is run even when all the recipients have been discarded. *\/ \/*XXS could we avoid this for the standard case, given that few people will use it? *\/ lseek(data_fd, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); \/* Arrange to catch crashes in local_scan(), so that the -D file gets deleted, and the incident gets logged. *\/ os_non_restarting_signal(SIGSEGV, local_scan_crash_handler); os_non_restarting_signal(SIGFPE, local_scan_crash_handler); os_non_restarting_signal(SIGILL, local_scan_crash_handler); os_non_restarting_signal(SIGBUS, local_scan_crash_handler); DEBUG(D_receive) debug_printf(\"calling local_scan(); timeout=%d\\n\", local_scan_timeout); local_scan_data = NULL; os_non_restarting_signal(SIGALRM, local_scan_timeout_handler); if (local_scan_timeout > 0) alarm(local_scan_timeout); rc = local_scan(data_fd, &local_scan_data); alarm(0); os_non_restarting_signal(SIGALRM, sigalrm_handler); enable_dollar_recipients = FALSE; store_pool = POOL_MAIN; \/* In case changed *\/ DEBUG(D_receive) debug_printf(\"local_scan() returned %d %s\\n\", rc, local_scan_data); os_non_restarting_signal(SIGSEGV, SIG_DFL); os_non_restarting_signal(SIGFPE, SIG_DFL); os_non_restarting_signal(SIGILL, SIG_DFL); os_non_restarting_signal(SIGBUS, SIG_DFL); \/* The length check is paranoia against some runaway code, and also because (for a success return) lines in the spool file are read into big_buffer. *\/ if (local_scan_data != NULL) { int len = Ustrlen(local_scan_data); if (len > LOCAL_SCAN_MAX_RETURN) len = LOCAL_SCAN_MAX_RETURN; local_scan_data = string_copyn(local_scan_data, len); } if (rc == LOCAL_SCAN_ACCEPT_FREEZE) { if (!deliver_freeze) \/* ACL might have already frozen *\/ { deliver_freeze = TRUE; deliver_frozen_at = time(NULL); frozen_by = US\"local_scan()\"; } rc = LOCAL_SCAN_ACCEPT; } else if (rc == LOCAL_SCAN_ACCEPT_QUEUE) { if (!queue_only_policy) \/* ACL might have already queued *\/ { queue_only_policy = TRUE; queued_by = US\"local_scan()\"; } rc = LOCAL_SCAN_ACCEPT; } \/* Message accepted: remove newlines in local_scan_data because otherwise the spool file gets corrupted. Ensure that all recipients are qualified. *\/ if (rc == LOCAL_SCAN_ACCEPT) { if (local_scan_data != NULL) { uschar *s; for (s = local_scan_data; *s != 0; s++) if (*s == '\\n') *s = ' '; } for (i = 0; i < recipients_count; i++) { recipient_item *r = recipients_list + i; r->address = rewrite_address_qualify(r->address, TRUE); if (r->errors_to != NULL) r->errors_to = rewrite_address_qualify(r->errors_to, TRUE); } if (recipients_count == 0 && blackholed_by == NULL) blackholed_by = US\"local_scan\"; } \/* Message rejected: newlines permitted in local_scan_data to generate multiline SMTP responses. *\/ else { uschar *istemp = US\"\"; uschar *smtp_code; gstring * g; errmsg = local_scan_data; Uunlink(spool_name); \/* Cancel this message *\/ switch(rc) { default: log_write(0, LOG_MAIN, \"invalid return %d from local_scan(). Temporary \" \"rejection given\", rc); goto TEMPREJECT; case LOCAL_SCAN_REJECT_NOLOGHDR: BIT_CLEAR(log_selector, log_selector_size, Li_rejected_header); \/* Fall through *\/ case LOCAL_SCAN_REJECT: smtp_code = US\"550\"; if (errmsg == NULL) errmsg = US\"Administrative prohibition\"; break; case LOCAL_SCAN_TEMPREJECT_NOLOGHDR: BIT_CLEAR(log_selector, log_selector_size, Li_rejected_header); \/* Fall through *\/ case LOCAL_SCAN_TEMPREJECT: TEMPREJECT: smtp_code = US\"451\"; if (errmsg == NULL) errmsg = US\"Temporary local problem\"; istemp = US\"temporarily \"; break; } g = string_append(g, 2, US\"F=\", sender_address[0] == 0 ? US\"<>\" : sender_address); g = add_host_info_for_log(g); log_write(0, LOG_MAIN|LOG_REJECT, \"%s %srejected by local_scan(): %.256s\", string_from_gstring(g), istemp, string_printing(errmsg)); if (smtp_input) { if (!smtp_batched_input) { smtp_respond(smtp_code, 3, TRUE, errmsg); message_id[0] = 0; \/* Indicate no message accepted *\/ smtp_reply = US\"\"; \/* Indicate reply already sent *\/ goto TIDYUP; \/* Skip to end of function *\/ } else { moan_smtp_batch(NULL, \"%s %s\", smtp_code, errmsg); \/* Does not return *\/ } } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_LOCAL_SCAN, errmsg, US\"message rejected by local scan code: \", error_rc, data_file, header_list); \/* Does not return *\/ } } \/* Reset signal handlers to ignore signals that previously would have caused the message to be abandoned. *\/ signal(SIGTERM, SIG_IGN); signal(SIGINT, SIG_IGN); \/* Ensure the first time flag is set in the newly-received message. *\/ deliver_firsttime = TRUE; #ifdef EXPERIMENTAL_BRIGHTMAIL if (bmi_run == 1) { \/* rewind data file *\/ lseek(data_fd, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); bmi_verdicts = bmi_process_message(header_list, data_fd); } #endif \/* Update the timestamp in our Received: header to account for any time taken by an ACL or by local_scan(). The new time is the time that all reception processing is complete. *\/ timestamp = expand_string(US\"${tod_full}\"); tslen = Ustrlen(timestamp); memcpy(received_header->text + received_header->slen - tslen - 1, timestamp, tslen); \/* In MUA wrapper mode, ignore queueing actions set by ACL or local_scan() *\/ if (mua_wrapper) { deliver_freeze = FALSE; queue_only_policy = FALSE; } \/* Keep the data file open until we have written the header file, in order to hold onto the lock. In a -bh run, or if the message is to be blackholed, we don't write the header file, and we unlink the data file. If writing the header file fails, we have failed to accept this message. *\/ if (host_checking || blackholed_by != NULL) { header_line *h; Uunlink(spool_name); msg_size = 0; \/* Compute size for log line *\/ for (h = header_list; h != NULL; h = h->next) if (h->type != '*') msg_size += h->slen; } \/* Write the -H file *\/ else if ((msg_size = spool_write_header(message_id, SW_RECEIVING, &errmsg)) < 0) { log_write(0, LOG_MAIN, \"Message abandoned: %s\", errmsg); Uunlink(spool_name); \/* Lose the data file *\/ if (smtp_input) { smtp_reply = US\"451 Error in writing spool file\"; message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_IOERR, errmsg, US\"\", error_rc, data_file, header_list); \/* Does not return *\/ } } \/* The message has now been successfully received. *\/ receive_messagecount++; \/* In SMTP sessions we may receive several in one connection. After each one, we wait for the clock to tick at the level of message-id granularity. This is so that the combination of time+pid is unique, even on systems where the pid can be re-used within our time interval. We can't shorten the interval without re-designing the message-id. See comments above where the message id is created. This is Something For The Future. *\/ message_id_tv.tv_usec = (message_id_tv.tv_usec\/id_resolution) * id_resolution; exim_wait_tick(&message_id_tv, id_resolution); \/* Add data size to written header size. We do not count the initial file name that is in the file, but we do add one extra for the notional blank line that precedes the data. This total differs from message_size in that it include the added Received: header and any other headers that got created locally. *\/ fflush(data_file); fstat(data_fd, &statbuf); msg_size += statbuf.st_size - SPOOL_DATA_START_OFFSET + 1; \/* Generate a \"message received\" log entry. We do this by building up a dynamic string as required. Since we commonly want to add two items at a time, use a macro to simplify the coding. We log the arrival of a new message while the file is still locked, just in case the machine is *really* fast, and delivers it first! Include any message id that is in the message - since the syntax of a message id is actually an addr-spec, we can use the parse routine to canonicalize it. *\/ g = string_get(256); g = string_append(g, 2, fake_response == FAIL ? US\"(= \" : US\"<= \", sender_address[0] == 0 ? US\"<>\" : sender_address); if (message_reference) g = string_append(g, 2, US\" R=\", message_reference); g = add_host_info_for_log(g); #ifdef SUPPORT_TLS if (LOGGING(tls_cipher) && tls_in.cipher) g = string_append(g, 2, US\" X=\", tls_in.cipher); if (LOGGING(tls_certificate_verified) && tls_in.cipher) g = string_append(g, 2, US\" CV=\", tls_in.certificate_verified ? \"yes\":\"no\"); if (LOGGING(tls_peerdn) && tls_in.peerdn) g = string_append(g, 3, US\" DN=\\\"\", string_printing(tls_in.peerdn), US\"\\\"\"); if (LOGGING(tls_sni) && tls_in.sni) g = string_append(g, 3, US\" SNI=\\\"\", string_printing(tls_in.sni), US\"\\\"\"); #endif if (sender_host_authenticated) { g = string_append(g, 2, US\" A=\", sender_host_authenticated); if (authenticated_id) { g = string_append(g, 2, US\":\", authenticated_id); if (LOGGING(smtp_mailauth) && authenticated_sender) g = string_append(g, 2, US\":\", authenticated_sender); } } #ifndef DISABLE_PRDR if (prdr_requested) g = string_catn(g, US\" PRDR\", 5); #endif #ifdef SUPPORT_PROXY if (proxy_session && LOGGING(proxy)) g = string_append(g, 2, US\" PRX=\", proxy_local_address); #endif if (chunking_state > CHUNKING_OFFERED) g = string_catn(g, US\" K\", 2); sprintf(CS big_buffer, \"%d\", msg_size); g = string_append(g, 2, US\" S=\", big_buffer); \/* log 8BITMIME mode announced in MAIL_FROM 0 ... no BODY= used 7 ... 7BIT 8 ... 8BITMIME *\/ if (LOGGING(8bitmime)) { sprintf(CS big_buffer, \"%d\", body_8bitmime); g = string_append(g, 2, US\" M8S=\", big_buffer); } if (*queue_name) g = string_append(g, 2, US\" Q=\", queue_name); \/* If an addr-spec in a message-id contains a quoted string, it can contain any characters except \" \\ and CR and so in particular it can contain NL! Therefore, make sure we use a printing-characters only version for the log. Also, allow for domain literals in the message id. *\/ if (msgid_header) { uschar *old_id; BOOL save_allow_domain_literals = allow_domain_literals; allow_domain_literals = TRUE; old_id = parse_extract_address(Ustrchr(msgid_header->text, ':') + 1, &errmsg, &start, &end, &domain, FALSE); allow_domain_literals = save_allow_domain_literals; if (old_id != NULL) g = string_append(g, 2, US\" id=\", string_printing(old_id)); } \/* If subject logging is turned on, create suitable printing-character text. By expanding $h_subject: we make use of the MIME decoding. *\/ if (LOGGING(subject) && subject_header != NULL) { int i; uschar *p = big_buffer; uschar *ss = expand_string(US\"$h_subject:\"); \/* Backslash-quote any double quotes or backslashes so as to make a a C-like string, and turn any non-printers into escape sequences. *\/ *p++ = '\\\"'; if (*ss != 0) for (i = 0; i < 100 && ss[i] != 0; i++) { if (ss[i] == '\\\"' || ss[i] == '\\\\') *p++ = '\\\\'; *p++ = ss[i]; } *p++ = '\\\"'; *p = 0; g = string_append(g, 2, US\" T=\", string_printing(big_buffer)); } \/* Terminate the string: string_cat() and string_append() leave room, but do not put the zero in. *\/ (void) string_from_gstring(g); \/* Create a message log file if message logs are being used and this message is not blackholed. Write the reception stuff to it. We used to leave message log creation until the first delivery, but this has proved confusing for some people. *\/ if (message_logs && !blackholed_by) { int fd; spool_name = spool_fname(US\"msglog\", message_subdir, message_id, US\"\"); if ( (fd = Uopen(spool_name, O_WRONLY|O_APPEND|O_CREAT, SPOOL_MODE)) < 0 && errno == ENOENT ) { (void)directory_make(spool_directory, spool_sname(US\"msglog\", message_subdir), MSGLOG_DIRECTORY_MODE, TRUE); fd = Uopen(spool_name, O_WRONLY|O_APPEND|O_CREAT, SPOOL_MODE); } if (fd < 0) log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't open message log %s: %s\", spool_name, strerror(errno)); else { FILE *message_log = fdopen(fd, \"a\"); if (message_log == NULL) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't fdopen message log %s: %s\", spool_name, strerror(errno)); (void)close(fd); } else { uschar *now = tod_stamp(tod_log); fprintf(message_log, \"%s Received from %s\\n\", now, g->s+3); if (deliver_freeze) fprintf(message_log, \"%s frozen by %s\\n\", now, frozen_by); if (queue_only_policy) fprintf(message_log, \"%s no immediate delivery: queued%s%s by %s\\n\", now, *queue_name ? \" in \" : \"\", *queue_name ? CS queue_name : \"\", queued_by); (void)fclose(message_log); } } } \/* Everything has now been done for a successful message except logging its arrival, and outputting an SMTP response. While writing to the log, set a flag to cause a call to receive_bomb_out() if the log cannot be opened. *\/ receive_call_bombout = TRUE; \/* Before sending an SMTP response in a TCP\/IP session, we check to see if the connection has gone away. This can only be done if there is no unconsumed input waiting in the local input buffer. We can test for this by calling receive_smtp_buffered(). RFC 2920 (pipelining) explicitly allows for additional input to be sent following the final dot, so the presence of following input is not an error. If the connection is still present, but there is no unread input for the socket, the result of a select() call will be zero. If, however, the connection has gone away, or if there is pending input, the result of select() will be non-zero. The two cases can be distinguished by trying to read the next input character. If we succeed, we can unread it so that it remains in the local buffer for handling later. If not, the connection has been lost. Of course, since TCP\/IP is asynchronous, there is always a chance that the connection will vanish between the time of this test and the sending of the response, but the chance of this happening should be small. *\/ if (smtp_input && sender_host_address != NULL && !sender_host_notsocket && !receive_smtp_buffered()) { struct timeval tv; fd_set select_check; FD_ZERO(&select_check); FD_SET(fileno(smtp_in), &select_check); tv.tv_sec = 0; tv.tv_usec = 0; if (select(fileno(smtp_in) + 1, &select_check, NULL, NULL, &tv) != 0) { int c = (receive_getc)(GETC_BUFFER_UNLIMITED); if (c != EOF) (receive_ungetc)(c); else { smtp_notquit_exit(US\"connection-lost\", NULL, NULL); smtp_reply = US\"\"; \/* No attempt to send a response *\/ smtp_yield = FALSE; \/* Nothing more on this connection *\/ \/* Re-use the log line workspace *\/ g->ptr = 0; g = string_cat(g, US\"SMTP connection lost after final dot\"); g = add_host_info_for_log(g); log_write(0, LOG_MAIN, \"%s\", string_from_gstring(g)); \/* Delete the files for this aborted message. *\/ Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-H\")); Uunlink(spool_fname(US\"msglog\", message_subdir, message_id, US\"\")); goto TIDYUP; } } } \/* The connection has not gone away; we really are going to take responsibility for this message. *\/ \/* Cutthrough - had sender last-dot; assume we've sent (or bufferred) all data onward by now. Send dot onward. If accepted, wipe the spooled files, log as delivered and accept the sender's dot (below). If rejected: copy response to sender, wipe the spooled files, log appropriately. If temp-reject: normally accept to sender, keep the spooled file - unless defer=pass in which case pass temp-reject back to initiator and dump the files. Having the normal spool files lets us do data-filtering, and store\/forward on temp-reject. XXX We do not handle queue-only, freezing, or blackholes. *\/ if(cutthrough.fd >= 0 && cutthrough.delivery) { uschar * msg = cutthrough_finaldot(); \/* Ask the target system to accept the message *\/ \/* Logging was done in finaldot() *\/ switch(msg[0]) { case '2': \/* Accept. Do the same to the source; dump any spoolfiles. *\/ cutthrough_done = ACCEPTED; break; \/* message_id needed for SMTP accept below *\/ case '4': \/* Temp-reject. Keep spoolfiles and accept, unless defer-pass mode. ... for which, pass back the exact error *\/ if (cutthrough.defer_pass) smtp_reply = string_copy_malloc(msg); \/*FALLTRHOUGH*\/ default: \/* Unknown response, or error. Treat as temp-reject. *\/ cutthrough_done = TMP_REJ; \/* Avoid the usual immediate delivery attempt *\/ break; \/* message_id needed for SMTP accept below *\/ case '5': \/* Perm-reject. Do the same to the source. Dump any spoolfiles *\/ smtp_reply = string_copy_malloc(msg); \/* Pass on the exact error *\/ cutthrough_done = PERM_REJ; break; } } #ifndef DISABLE_PRDR if(!smtp_reply || prdr_requested) #else if(!smtp_reply) #endif { log_write(0, LOG_MAIN | (LOGGING(received_recipients)? LOG_RECIPIENTS : 0) | (LOGGING(received_sender)? LOG_SENDER : 0), \"%s\", g->s); \/* Log any control actions taken by an ACL or local_scan(). *\/ if (deliver_freeze) log_write(0, LOG_MAIN, \"frozen by %s\", frozen_by); if (queue_only_policy) log_write(L_delay_delivery, LOG_MAIN, \"no immediate delivery: queued%s%s by %s\", *queue_name ? \" in \" : \"\", *queue_name ? CS queue_name : \"\", queued_by); } receive_call_bombout = FALSE; store_reset(g); \/* The store for the main log message can be reused *\/ \/* If the message is frozen, and freeze_tell is set, do the telling. *\/ if (deliver_freeze && freeze_tell != NULL && freeze_tell[0] != 0) { moan_tell_someone(freeze_tell, NULL, US\"Message frozen on arrival\", \"Message %s was frozen on arrival by %s.\\nThe sender is <%s>.\\n\", message_id, frozen_by, sender_address); } \/* Either a message has been successfully received and written to the two spool files, or an error in writing the spool has occurred for an SMTP message, or an SMTP message has been rejected for policy reasons. (For a non-SMTP message we will have already given up because there's no point in carrying on!) In either event, we must now close (and thereby unlock) the data file. In the successful case, this leaves the message on the spool, ready for delivery. In the error case, the spool file will be deleted. Then tidy up store, interact with an SMTP call if necessary, and return. A fflush() was done earlier in the expectation that any write errors on the data file will be flushed(!) out thereby. Nevertheless, it is theoretically possible for fclose() to fail - but what to do? What has happened to the lock if this happens? *\/ TIDYUP: process_info[process_info_len] = 0; \/* Remove message id *\/ if (data_file != NULL) (void)fclose(data_file); \/* Frees the lock *\/ \/* Now reset signal handlers to their defaults *\/ signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL); \/* Tell an SMTP caller the state of play, and arrange to return the SMTP return value, which defaults TRUE - meaning there may be more incoming messages from this connection. For non-SMTP callers (where there is only ever one message), the default is FALSE. *\/ if (smtp_input) { yield = smtp_yield; \/* Handle interactive SMTP callers. After several kinds of error, smtp_reply is set to the response that should be sent. When it is NULL, we generate default responses. After an ACL error or local_scan() error, the response has already been sent, and smtp_reply is an empty string to indicate this. *\/ if (!smtp_batched_input) { if (!smtp_reply) { if (fake_response != OK) smtp_respond(fake_response == DEFER ? US\"450\" : US\"550\", 3, TRUE, fake_response_text); \/* An OK response is required; use \"message\" text if present. *\/ else if (user_msg) { uschar *code = US\"250\"; int len = 3; smtp_message_code(&code, &len, &user_msg, NULL, TRUE); smtp_respond(code, len, TRUE, user_msg); } \/* Default OK response *\/ else if (chunking_state > CHUNKING_OFFERED) { smtp_printf(\"250- %u byte chunk, total %d\\r\\n250 OK id=%s\\r\\n\", FALSE, chunking_datasize, message_size+message_linecount, message_id); chunking_state = CHUNKING_OFFERED; } else smtp_printf(\"250 OK id=%s\\r\\n\", FALSE, message_id); if (host_checking) fprintf(stdout, \"\\n**** SMTP testing: that is not a real message id!\\n\\n\"); } \/* smtp_reply is set non-empty *\/ else if (smtp_reply[0] != 0) if (fake_response != OK && (smtp_reply[0] == '2')) smtp_respond((fake_response == DEFER)? US\"450\" : US\"550\", 3, TRUE, fake_response_text); else smtp_printf(\"%.1024s\\r\\n\", FALSE, smtp_reply); switch (cutthrough_done) { case ACCEPTED: log_write(0, LOG_MAIN, \"Completed\");\/* Delivery was done *\/ case PERM_REJ: \/* Delete spool files *\/ Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-H\")); Uunlink(spool_fname(US\"msglog\", message_subdir, message_id, US\"\")); break; case TMP_REJ: if (cutthrough.defer_pass) { Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-H\")); Uunlink(spool_fname(US\"msglog\", message_subdir, message_id, US\"\")); } default: break; } if (cutthrough_done != NOT_TRIED) { message_id[0] = 0; \/* Prevent a delivery from starting *\/ cutthrough.delivery = cutthrough.callout_hold_only = FALSE; cutthrough.defer_pass = FALSE; } } \/* For batched SMTP, generate an error message on failure, and do nothing on success. The function moan_smtp_batch() does not return - it exits from the program with a non-zero return code. *\/ else if (smtp_reply) moan_smtp_batch(NULL, \"%s\", smtp_reply); } \/* If blackholing, we can immediately log this message's sad fate. The data file has already been unlinked, and the header file was never written to disk. We must now indicate that nothing was received, to prevent a delivery from starting. *\/ if (blackholed_by) { const uschar *detail = local_scan_data ? string_printing(local_scan_data) : string_sprintf(\"(%s discarded recipients)\", blackholed_by); log_write(0, LOG_MAIN, \"=> blackhole %s%s\", detail, blackhole_log_msg); log_write(0, LOG_MAIN, \"Completed\"); message_id[0] = 0; } \/* Reset headers so that logging of rejects for a subsequent message doesn't include them. It is also important to set header_last = NULL before exiting from this function, as this prevents certain rewrites that might happen during subsequent verifying (of another incoming message) from trying to add headers when they shouldn't. *\/ header_list = header_last = NULL; return yield; \/* TRUE if more messages (SMTP only) *\/ }","output":{"is_vulnerable":"True","vulnerability_types":["Use After Free"],"explanation":"The receive_msg function in receive.c in the SMTP daemon in Exim 4.88 and 4.89 allows remote attackers to execute arbitrary code or cause a denial of service (use-after-free) via vectors involving BDAT commands.","severity_level":"High","cwe":"CWE-416","cve":"CVE-2017-16943"}} -{"idx":466093,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char *name, s[2]; const char *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; if (image->depth != GetImageDepth(image,exception)) (void) SetImageDepth(image,image->depth,exception); for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *r; register Quantum *q; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { r=GetVirtualPixels(image,0,y,image->columns,1,exception); if (r == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,r) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image,r,opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,r,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image,r,opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,r) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image,r,transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,r); ping_trans_color.green=(unsigned short) GetPixelGreen(image,r); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,r); ping_trans_color.gray=(unsigned short) GetPixelGray(image,r); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,r,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,r,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,r,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,r,semitransparent+i) && GetPixelAlpha(image,r) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image,r,semitransparent+i); } } } r+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != GetPixelGreen(image,r) || GetPixelRed(image,r) != GetPixelBlue(image,r)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != 0 && GetPixelRed(image,r) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,q); SetPixelAlpha(image,TransparentAlpha,q); } else SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR04PixelRGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR03RGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR02PixelBlue(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,q)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,q)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,q)) == 0x00 && GetPixelAlpha(image,q) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } (void) old_bit_depth; image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); \/* write orNT if image->orientation is defined *\/ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); \/* data length=1 *\/ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); \/* PNG uses Exif orientation values *\/ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(ping_pixels,0,rowbytes*sizeof(*ping_pixels)); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { \/* Palette, Bilevel, or Opaque Monochrome *\/ QuantumType quantum_type; register const Quantum *p; quantum_type=RedQuantum; if (mng_info->IsPalette) { quantum_type=GrayQuantum; if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) quantum_type=IndexQuantum; } SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,ping_pixels,exception); if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":70685,"input":"VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp, const FCHAR_T *format, va_list args) { DIRECTIVES d; arguments a; if (PRINTF_PARSE (format, &d, &a) < 0) \/* errno is already set. *\/ return NULL; #define CLEANUP() \\ if (d.dir != d.direct_alloc_dir) \\ free (d.dir); \\ if (a.arg != a.direct_alloc_arg) \\ free (a.arg); if (PRINTF_FETCHARGS (args, &a) < 0) { CLEANUP (); errno = EINVAL; return NULL; } { size_t buf_neededlength; TCHAR_T *buf; TCHAR_T *buf_malloced; const FCHAR_T *cp; size_t i; DIRECTIVE *dp; \/* Output string accumulator. *\/ DCHAR_T *result; size_t allocated; size_t length; \/* Allocate a small buffer that will hold a directive passed to sprintf or snprintf. *\/ buf_neededlength = xsum4 (7, d.max_width_length, d.max_precision_length, 6); #if HAVE_ALLOCA if (buf_neededlength < 4000 \/ sizeof (TCHAR_T)) { buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T)); buf_malloced = NULL; } else #endif { size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T)); if (size_overflow_p (buf_memsize)) goto out_of_memory_1; buf = (TCHAR_T *) malloc (buf_memsize); if (buf == NULL) goto out_of_memory_1; buf_malloced = buf; } if (resultbuf != NULL) { result = resultbuf; allocated = *lengthp; } else { result = NULL; allocated = 0; } length = 0; \/* Invariants: result is either == resultbuf or == NULL or malloc-allocated. If length > 0, then result != NULL. *\/ \/* Ensures that allocated >= needed. Aborts through a jump to out_of_memory if needed is SIZE_MAX or otherwise too big. *\/ #define ENSURE_ALLOCATION(needed) \\ if ((needed) > allocated) \\ { \\ size_t memory_size; \\ DCHAR_T *memory; \\ \\ allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \\ if ((needed) > allocated) \\ allocated = (needed); \\ memory_size = xtimes (allocated, sizeof (DCHAR_T)); \\ if (size_overflow_p (memory_size)) \\ goto out_of_memory; \\ if (result == resultbuf || result == NULL) \\ memory = (DCHAR_T *) malloc (memory_size); \\ else \\ memory = (DCHAR_T *) realloc (result, memory_size); \\ if (memory == NULL) \\ goto out_of_memory; \\ if (result == resultbuf && length > 0) \\ DCHAR_CPY (memory, result, length); \\ result = memory; \\ } for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++) { if (cp != dp->dir_start) { size_t n = dp->dir_start - cp; size_t augmented_length = xsum (length, n); ENSURE_ALLOCATION (augmented_length); \/* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we need that the format string contains only ASCII characters if FCHAR_T and DCHAR_T are not the same type. *\/ if (sizeof (FCHAR_T) == sizeof (DCHAR_T)) { DCHAR_CPY (result + length, (const DCHAR_T *) cp, n); length = augmented_length; } else { do result[length++] = *cp++; while (--n > 0); } } if (i == d.count) break; \/* Execute a single directive. *\/ if (dp->conversion == '%') { size_t augmented_length; if (!(dp->arg_index == ARG_NONE)) abort (); augmented_length = xsum (length, 1); ENSURE_ALLOCATION (augmented_length); result[length] = '%'; length = augmented_length; } else { if (!(dp->arg_index != ARG_NONE)) abort (); if (dp->conversion == 'n') { switch (a.arg[dp->arg_index].type) { case TYPE_COUNT_SCHAR_POINTER: *a.arg[dp->arg_index].a.a_count_schar_pointer = length; break; case TYPE_COUNT_SHORT_POINTER: *a.arg[dp->arg_index].a.a_count_short_pointer = length; break; case TYPE_COUNT_INT_POINTER: *a.arg[dp->arg_index].a.a_count_int_pointer = length; break; case TYPE_COUNT_LONGINT_POINTER: *a.arg[dp->arg_index].a.a_count_longint_pointer = length; break; #if HAVE_LONG_LONG_INT case TYPE_COUNT_LONGLONGINT_POINTER: *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length; break; #endif default: abort (); } } #if ENABLE_UNISTDIO \/* The unistdio extensions. *\/ else if (dp->conversion == 'U') { arg_type type = a.arg[dp->arg_index].type; int flags = dp->flags; int has_width; size_t width; int has_precision; size_t precision; has_width = 0; width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { \/* \"A negative field width is taken as a '-' flag followed by a positive field width.\" *\/ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } has_width = 1; } has_precision = 0; precision = 0; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; \/* \"A negative precision is taken as if the precision were omitted.\" *\/ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } switch (type) { case TYPE_U8_STRING: { const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string; const uint8_t *arg_end; size_t characters; if (has_precision) { \/* Use only PRECISION characters, from the left. *\/ arg_end = arg; characters = 0; for (; precision > 0; precision--) { int count = u8_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else if (has_width) { \/* Use the entire string, and count the number of characters. *\/ arg_end = arg; characters = 0; for (;;) { int count = u8_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else { \/* Use the entire string. *\/ arg_end = arg + u8_strlen (arg); \/* The number of characters doesn't matter. *\/ characters = 0; } if (characters < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } # if DCHAR_IS_UINT8_T { size_t n = arg_end - arg; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_CPY (result + length, arg, n); length += n; } # else { \/* Convert. *\/ DCHAR_T *converted = result + length; size_t converted_len = allocated - length; # if DCHAR_IS_TCHAR \/* Convert from UTF-8 to locale encoding. *\/ converted = u8_conv_to_encoding (locale_charset (), iconveh_question_mark, arg, arg_end - arg, NULL, converted, &converted_len); # else \/* Convert from UTF-8 to UTF-16\/UTF-32. *\/ converted = U8_TO_DCHAR (arg, arg_end - arg, converted, &converted_len); # endif if (converted == NULL) { int saved_errno = errno; if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } if (converted != result + length) { ENSURE_ALLOCATION (xsum (length, converted_len)); DCHAR_CPY (result + length, converted, converted_len); free (converted); } length += converted_len; } # endif if (characters < width && (dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } break; case TYPE_U16_STRING: { const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string; const uint16_t *arg_end; size_t characters; if (has_precision) { \/* Use only PRECISION characters, from the left. *\/ arg_end = arg; characters = 0; for (; precision > 0; precision--) { int count = u16_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else if (has_width) { \/* Use the entire string, and count the number of characters. *\/ arg_end = arg; characters = 0; for (;;) { int count = u16_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else { \/* Use the entire string. *\/ arg_end = arg + u16_strlen (arg); \/* The number of characters doesn't matter. *\/ characters = 0; } if (characters < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } # if DCHAR_IS_UINT16_T { size_t n = arg_end - arg; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_CPY (result + length, arg, n); length += n; } # else { \/* Convert. *\/ DCHAR_T *converted = result + length; size_t converted_len = allocated - length; # if DCHAR_IS_TCHAR \/* Convert from UTF-16 to locale encoding. *\/ converted = u16_conv_to_encoding (locale_charset (), iconveh_question_mark, arg, arg_end - arg, NULL, converted, &converted_len); # else \/* Convert from UTF-16 to UTF-8\/UTF-32. *\/ converted = U16_TO_DCHAR (arg, arg_end - arg, converted, &converted_len); # endif if (converted == NULL) { int saved_errno = errno; if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } if (converted != result + length) { ENSURE_ALLOCATION (xsum (length, converted_len)); DCHAR_CPY (result + length, converted, converted_len); free (converted); } length += converted_len; } # endif if (characters < width && (dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } break; case TYPE_U32_STRING: { const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string; const uint32_t *arg_end; size_t characters; if (has_precision) { \/* Use only PRECISION characters, from the left. *\/ arg_end = arg; characters = 0; for (; precision > 0; precision--) { int count = u32_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else if (has_width) { \/* Use the entire string, and count the number of characters. *\/ arg_end = arg; characters = 0; for (;;) { int count = u32_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else { \/* Use the entire string. *\/ arg_end = arg + u32_strlen (arg); \/* The number of characters doesn't matter. *\/ characters = 0; } if (characters < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } # if DCHAR_IS_UINT32_T { size_t n = arg_end - arg; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_CPY (result + length, arg, n); length += n; } # else { \/* Convert. *\/ DCHAR_T *converted = result + length; size_t converted_len = allocated - length; # if DCHAR_IS_TCHAR \/* Convert from UTF-32 to locale encoding. *\/ converted = u32_conv_to_encoding (locale_charset (), iconveh_question_mark, arg, arg_end - arg, NULL, converted, &converted_len); # else \/* Convert from UTF-32 to UTF-8\/UTF-16. *\/ converted = U32_TO_DCHAR (arg, arg_end - arg, converted, &converted_len); # endif if (converted == NULL) { int saved_errno = errno; if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } if (converted != result + length) { ENSURE_ALLOCATION (xsum (length, converted_len)); DCHAR_CPY (result + length, converted, converted_len); free (converted); } length += converted_len; } # endif if (characters < width && (dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } break; default: abort (); } } #endif #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T else if (dp->conversion == 's' # if WIDE_CHAR_VERSION && a.arg[dp->arg_index].type != TYPE_WIDE_STRING # else && a.arg[dp->arg_index].type == TYPE_WIDE_STRING # endif ) { \/* The normal handling of the 's' directive below requires allocating a temporary buffer. The determination of its length (tmp_length), in the case when a precision is specified, below requires a conversion between a char[] string and a wchar_t[] wide string. It could be done, but we have no guarantee that the implementation of sprintf will use the exactly same algorithm. Without this guarantee, it is possible to have buffer overrun bugs. In order to avoid such bugs, we implement the entire processing of the 's' directive ourselves. *\/ int flags = dp->flags; int has_width; size_t width; int has_precision; size_t precision; has_width = 0; width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { \/* \"A negative field width is taken as a '-' flag followed by a positive field width.\" *\/ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } has_width = 1; } has_precision = 0; precision = 6; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; \/* \"A negative precision is taken as if the precision were omitted.\" *\/ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } # if WIDE_CHAR_VERSION \/* %s in vasnwprintf. See the specification of fwprintf. *\/ { const char *arg = a.arg[dp->arg_index].a.a_string; const char *arg_end; size_t characters; if (has_precision) { \/* Use only as many bytes as needed to produce PRECISION wide characters, from the left. *\/ # if HAVE_MBRTOWC mbstate_t state; memset (&state, '\\0', sizeof (mbstate_t)); # endif arg_end = arg; characters = 0; for (; precision > 0; precision--) { int count; # if HAVE_MBRTOWC count = mbrlen (arg_end, MB_CUR_MAX, &state); # else count = mblen (arg_end, MB_CUR_MAX); # endif if (count == 0) \/* Found the terminating NUL. *\/ break; if (count < 0) { \/* Invalid or incomplete multibyte character. *\/ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else if (has_width) { \/* Use the entire string, and count the number of wide characters. *\/ # if HAVE_MBRTOWC mbstate_t state; memset (&state, '\\0', sizeof (mbstate_t)); # endif arg_end = arg; characters = 0; for (;;) { int count; # if HAVE_MBRTOWC count = mbrlen (arg_end, MB_CUR_MAX, &state); # else count = mblen (arg_end, MB_CUR_MAX); # endif if (count == 0) \/* Found the terminating NUL. *\/ break; if (count < 0) { \/* Invalid or incomplete multibyte character. *\/ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else { \/* Use the entire string. *\/ arg_end = arg + strlen (arg); \/* The number of characters doesn't matter. *\/ characters = 0; } if (characters < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } if (has_precision || has_width) { \/* We know the number of wide characters in advance. *\/ size_t remaining; # if HAVE_MBRTOWC mbstate_t state; memset (&state, '\\0', sizeof (mbstate_t)); # endif ENSURE_ALLOCATION (xsum (length, characters)); for (remaining = characters; remaining > 0; remaining--) { wchar_t wc; int count; # if HAVE_MBRTOWC count = mbrtowc (&wc, arg, arg_end - arg, &state); # else count = mbtowc (&wc, arg, arg_end - arg); # endif if (count <= 0) \/* mbrtowc not consistent with mbrlen, or mbtowc not consistent with mblen. *\/ abort (); result[length++] = wc; arg += count; } if (!(arg == arg_end)) abort (); } else { # if HAVE_MBRTOWC mbstate_t state; memset (&state, '\\0', sizeof (mbstate_t)); # endif while (arg < arg_end) { wchar_t wc; int count; # if HAVE_MBRTOWC count = mbrtowc (&wc, arg, arg_end - arg, &state); # else count = mbtowc (&wc, arg, arg_end - arg); # endif if (count <= 0) \/* mbrtowc not consistent with mbrlen, or mbtowc not consistent with mblen. *\/ abort (); ENSURE_ALLOCATION (xsum (length, 1)); result[length++] = wc; arg += count; } } if (characters < width && (dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } # else \/* %ls in vasnprintf. See the specification of fprintf. *\/ { const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string; const wchar_t *arg_end; size_t characters; # if !DCHAR_IS_TCHAR \/* This code assumes that TCHAR_T is 'char'. *\/ verify (sizeof (TCHAR_T) == 1); TCHAR_T *tmpsrc; DCHAR_T *tmpdst; size_t tmpdst_len; # endif size_t w; if (has_precision) { \/* Use only as many wide characters as needed to produce at most PRECISION bytes, from the left. *\/ # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\\0', sizeof (mbstate_t)); # endif arg_end = arg; characters = 0; while (precision > 0) { char cbuf[64]; \/* Assume MB_CUR_MAX <= 64. *\/ int count; if (*arg_end == 0) \/* Found the terminating null wide character. *\/ break; # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg_end, &state); # else count = wctomb (cbuf, *arg_end); # endif if (count < 0) { \/* Cannot convert. *\/ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } if (precision < count) break; arg_end++; characters += count; precision -= count; } } # if DCHAR_IS_TCHAR else if (has_width) # else else # endif { \/* Use the entire string, and count the number of bytes. *\/ # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\\0', sizeof (mbstate_t)); # endif arg_end = arg; characters = 0; for (;;) { char cbuf[64]; \/* Assume MB_CUR_MAX <= 64. *\/ int count; if (*arg_end == 0) \/* Found the terminating null wide character. *\/ break; # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg_end, &state); # else count = wctomb (cbuf, *arg_end); # endif if (count < 0) { \/* Cannot convert. *\/ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end++; characters += count; } } # if DCHAR_IS_TCHAR else { \/* Use the entire string. *\/ arg_end = arg + local_wcslen (arg); \/* The number of bytes doesn't matter. *\/ characters = 0; } # endif # if !DCHAR_IS_TCHAR \/* Convert the string into a piece of temporary memory. *\/ tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T)); if (tmpsrc == NULL) goto out_of_memory; { TCHAR_T *tmpptr = tmpsrc; size_t remaining; # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\\0', sizeof (mbstate_t)); # endif for (remaining = characters; remaining > 0; ) { char cbuf[64]; \/* Assume MB_CUR_MAX <= 64. *\/ int count; if (*arg == 0) abort (); # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg, &state); # else count = wctomb (cbuf, *arg); # endif if (count <= 0) \/* Inconsistency. *\/ abort (); memcpy (tmpptr, cbuf, count); tmpptr += count; arg++; remaining -= count; } if (!(arg == arg_end)) abort (); } \/* Convert from TCHAR_T[] to DCHAR_T[]. *\/ tmpdst = DCHAR_CONV_FROM_ENCODING (locale_charset (), iconveh_question_mark, tmpsrc, characters, NULL, NULL, &tmpdst_len); if (tmpdst == NULL) { int saved_errno = errno; free (tmpsrc); if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } free (tmpsrc); # endif if (has_width) { # if ENABLE_UNISTDIO \/* Outside POSIX, it's preferable to compare the width against the number of _characters_ of the converted value. *\/ w = DCHAR_MBSNLEN (result + length, characters); # else \/* The width is compared against the number of _bytes_ of the converted value, says POSIX. *\/ w = characters; # endif } else \/* w doesn't matter. *\/ w = 0; if (w < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - w; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } # if DCHAR_IS_TCHAR if (has_precision || has_width) { \/* We know the number of bytes in advance. *\/ size_t remaining; # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\\0', sizeof (mbstate_t)); # endif ENSURE_ALLOCATION (xsum (length, characters)); for (remaining = characters; remaining > 0; ) { char cbuf[64]; \/* Assume MB_CUR_MAX <= 64. *\/ int count; if (*arg == 0) abort (); # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg, &state); # else count = wctomb (cbuf, *arg); # endif if (count <= 0) \/* Inconsistency. *\/ abort (); memcpy (result + length, cbuf, count); length += count; arg++; remaining -= count; } if (!(arg == arg_end)) abort (); } else { # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\\0', sizeof (mbstate_t)); # endif while (arg < arg_end) { char cbuf[64]; \/* Assume MB_CUR_MAX <= 64. *\/ int count; if (*arg == 0) abort (); # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg, &state); # else count = wctomb (cbuf, *arg); # endif if (count <= 0) { \/* Cannot convert. *\/ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } ENSURE_ALLOCATION (xsum (length, count)); memcpy (result + length, cbuf, count); length += count; arg++; } } # else ENSURE_ALLOCATION (xsum (length, tmpdst_len)); DCHAR_CPY (result + length, tmpdst, tmpdst_len); free (tmpdst); length += tmpdst_len; # endif if (w < width && (dp->flags & FLAG_LEFT)) { size_t n = width - w; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } # endif } #endif #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL else if ((dp->conversion == 'a' || dp->conversion == 'A') # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE)) && (0 # if NEED_PRINTF_DOUBLE || a.arg[dp->arg_index].type == TYPE_DOUBLE # endif # if NEED_PRINTF_LONG_DOUBLE || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE # endif ) # endif ) { arg_type type = a.arg[dp->arg_index].type; int flags = dp->flags; size_t width; int has_precision; size_t precision; size_t tmp_length; size_t count; DCHAR_T tmpbuf[700]; DCHAR_T *tmp; DCHAR_T *pad_ptr; DCHAR_T *p; width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { \/* \"A negative field width is taken as a '-' flag followed by a positive field width.\" *\/ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } } has_precision = 0; precision = 0; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; \/* \"A negative precision is taken as if the precision were omitted.\" *\/ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } \/* Allocate a temporary buffer of sufficient size. *\/ if (type == TYPE_LONGDOUBLE) tmp_length = (unsigned int) ((LDBL_DIG + 1) * 0.831 \/* decimal -> hexadecimal *\/ ) + 1; \/* turn floor into ceil *\/ else tmp_length = (unsigned int) ((DBL_DIG + 1) * 0.831 \/* decimal -> hexadecimal *\/ ) + 1; \/* turn floor into ceil *\/ if (tmp_length < precision) tmp_length = precision; \/* Account for sign, decimal point etc. *\/ tmp_length = xsum (tmp_length, 12); if (tmp_length < width) tmp_length = width; tmp_length = xsum (tmp_length, 1); \/* account for trailing NUL *\/ if (tmp_length <= sizeof (tmpbuf) \/ sizeof (DCHAR_T)) tmp = tmpbuf; else { size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T)); if (size_overflow_p (tmp_memsize)) \/* Overflow, would lead to out of memory. *\/ goto out_of_memory; tmp = (DCHAR_T *) malloc (tmp_memsize); if (tmp == NULL) \/* Out of memory. *\/ goto out_of_memory; } pad_ptr = NULL; p = tmp; if (type == TYPE_LONGDOUBLE) { # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE long double arg = a.arg[dp->arg_index].a.a_longdouble; if (isnanl (arg)) { if (dp->conversion == 'A') { *p++ = 'N'; *p++ = 'A'; *p++ = 'N'; } else { *p++ = 'n'; *p++ = 'a'; *p++ = 'n'; } } else { int sign = 0; DECL_LONG_DOUBLE_ROUNDING BEGIN_LONG_DOUBLE_ROUNDING (); if (signbit (arg)) \/* arg < 0.0L or negative zero *\/ { sign = -1; arg = -arg; } if (sign < 0) *p++ = '-'; else if (flags & FLAG_SHOWSIGN) *p++ = '+'; else if (flags & FLAG_SPACE) *p++ = ' '; if (arg > 0.0L && arg + arg == arg) { if (dp->conversion == 'A') { *p++ = 'I'; *p++ = 'N'; *p++ = 'F'; } else { *p++ = 'i'; *p++ = 'n'; *p++ = 'f'; } } else { int exponent; long double mantissa; if (arg > 0.0L) mantissa = printf_frexpl (arg, &exponent); else { exponent = 0; mantissa = 0.0L; } if (has_precision && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1) { \/* Round the mantissa. *\/ long double tail = mantissa; size_t q; for (q = precision; ; q--) { int digit = (int) tail; tail -= digit; if (q == 0) { if (digit & 1 ? tail >= 0.5L : tail > 0.5L) tail = 1 - tail; else tail = - tail; break; } tail *= 16.0L; } if (tail != 0.0L) for (q = precision; q > 0; q--) tail *= 0.0625L; mantissa += tail; } *p++ = '0'; *p++ = dp->conversion - 'A' + 'X'; pad_ptr = p; { int digit; digit = (int) mantissa; mantissa -= digit; *p++ = '0' + digit; if ((flags & FLAG_ALT) || mantissa > 0.0L || precision > 0) { *p++ = decimal_point_char (); \/* This loop terminates because we assume that FLT_RADIX is a power of 2. *\/ while (mantissa > 0.0L) { mantissa *= 16.0L; digit = (int) mantissa; mantissa -= digit; *p++ = digit + (digit < 10 ? '0' : dp->conversion - 10); if (precision > 0) precision--; } while (precision > 0) { *p++ = '0'; precision--; } } } *p++ = dp->conversion - 'A' + 'P'; # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = { '%', '+', 'd', '\\0' }; SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\\0') p++; # else if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, \"%+d\", exponent); while (*p != '\\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, \"%+d\", exponent); for (ep = expbuf; (*p = *ep) != '\\0'; ep++) p++; } # endif } END_LONG_DOUBLE_ROUNDING (); } # else abort (); # endif } else { # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE double arg = a.arg[dp->arg_index].a.a_double; if (isnand (arg)) { if (dp->conversion == 'A') { *p++ = 'N'; *p++ = 'A'; *p++ = 'N'; } else { *p++ = 'n'; *p++ = 'a'; *p++ = 'n'; } } else { int sign = 0; if (signbit (arg)) \/* arg < 0.0 or negative zero *\/ { sign = -1; arg = -arg; } if (sign < 0) *p++ = '-'; else if (flags & FLAG_SHOWSIGN) *p++ = '+'; else if (flags & FLAG_SPACE) *p++ = ' '; if (arg > 0.0 && arg + arg == arg) { if (dp->conversion == 'A') { *p++ = 'I'; *p++ = 'N'; *p++ = 'F'; } else { *p++ = 'i'; *p++ = 'n'; *p++ = 'f'; } } else { int exponent; double mantissa; if (arg > 0.0) mantissa = printf_frexp (arg, &exponent); else { exponent = 0; mantissa = 0.0; } if (has_precision && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1) { \/* Round the mantissa. *\/ double tail = mantissa; size_t q; for (q = precision; ; q--) { int digit = (int) tail; tail -= digit; if (q == 0) { if (digit & 1 ? tail >= 0.5 : tail > 0.5) tail = 1 - tail; else tail = - tail; break; } tail *= 16.0; } if (tail != 0.0) for (q = precision; q > 0; q--) tail *= 0.0625; mantissa += tail; } *p++ = '0'; *p++ = dp->conversion - 'A' + 'X'; pad_ptr = p; { int digit; digit = (int) mantissa; mantissa -= digit; *p++ = '0' + digit; if ((flags & FLAG_ALT) || mantissa > 0.0 || precision > 0) { *p++ = decimal_point_char (); \/* This loop terminates because we assume that FLT_RADIX is a power of 2. *\/ while (mantissa > 0.0) { mantissa *= 16.0; digit = (int) mantissa; mantissa -= digit; *p++ = digit + (digit < 10 ? '0' : dp->conversion - 10); if (precision > 0) precision--; } while (precision > 0) { *p++ = '0'; precision--; } } } *p++ = dp->conversion - 'A' + 'P'; # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = { '%', '+', 'd', '\\0' }; SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\\0') p++; # else if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, \"%+d\", exponent); while (*p != '\\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, \"%+d\", exponent); for (ep = expbuf; (*p = *ep) != '\\0'; ep++) p++; } # endif } } # else abort (); # endif } \/* The generated string now extends from tmp to p, with the zero padding insertion point being at pad_ptr. *\/ count = p - tmp; if (count < width) { size_t pad = width - count; DCHAR_T *end = p + pad; if (flags & FLAG_LEFT) { \/* Pad with spaces on the right. *\/ for (; pad > 0; pad--) *p++ = ' '; } else if ((flags & FLAG_ZERO) && pad_ptr != NULL) { \/* Pad with zeroes. *\/ DCHAR_T *q = end; while (p > pad_ptr) *--q = *--p; for (; pad > 0; pad--) *p++ = '0'; } else { \/* Pad with spaces on the left. *\/ DCHAR_T *q = end; while (p > tmp) *--q = *--p; for (; pad > 0; pad--) *p++ = ' '; } p = end; } count = p - tmp; if (count >= tmp_length) \/* tmp_length was incorrectly calculated - fix the code above! *\/ abort (); \/* Make room for the result. *\/ if (count >= allocated - length) { size_t n = xsum (length, count); ENSURE_ALLOCATION (n); } \/* Append the result. *\/ memcpy (result + length, tmp, count * sizeof (DCHAR_T)); if (tmp != tmpbuf) free (tmp); length += count; } #endif #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL else if ((dp->conversion == 'f' || dp->conversion == 'F' || dp->conversion == 'e' || dp->conversion == 'E' || dp->conversion == 'g' || dp->conversion == 'G' || dp->conversion == 'a' || dp->conversion == 'A') && (0 # if NEED_PRINTF_DOUBLE || a.arg[dp->arg_index].type == TYPE_DOUBLE # elif NEED_PRINTF_INFINITE_DOUBLE || (a.arg[dp->arg_index].type == TYPE_DOUBLE \/* The systems (mingw) which produce wrong output for Inf, -Inf, and NaN also do so for -0.0. Therefore we treat this case here as well. *\/ && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double)) # endif # if NEED_PRINTF_LONG_DOUBLE || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE # elif NEED_PRINTF_INFINITE_LONG_DOUBLE || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE \/* Some systems produce wrong output for Inf, -Inf, and NaN. Some systems in this category (IRIX 5.3) also do so for -0.0. Therefore we treat this case here as well. *\/ && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble)) # endif )) { # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) arg_type type = a.arg[dp->arg_index].type; # endif int flags = dp->flags; size_t width; size_t count; int has_precision; size_t precision; size_t tmp_length; DCHAR_T tmpbuf[700]; DCHAR_T *tmp; DCHAR_T *pad_ptr; DCHAR_T *p; width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { \/* \"A negative field width is taken as a '-' flag followed by a positive field width.\" *\/ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } } has_precision = 0; precision = 0; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; \/* \"A negative precision is taken as if the precision were omitted.\" *\/ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } \/* POSIX specifies the default precision to be 6 for %f, %F, %e, %E, but not for %g, %G. Implementations appear to use the same default precision also for %g, %G. But for %a, %A, the default precision is 0. *\/ if (!has_precision) if (!(dp->conversion == 'a' || dp->conversion == 'A')) precision = 6; \/* Allocate a temporary buffer of sufficient size. *\/ # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1); # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0); # elif NEED_PRINTF_LONG_DOUBLE tmp_length = LDBL_DIG + 1; # elif NEED_PRINTF_DOUBLE tmp_length = DBL_DIG + 1; # else tmp_length = 0; # endif if (tmp_length < precision) tmp_length = precision; # if NEED_PRINTF_LONG_DOUBLE # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE if (type == TYPE_LONGDOUBLE) # endif if (dp->conversion == 'f' || dp->conversion == 'F') { long double arg = a.arg[dp->arg_index].a.a_longdouble; if (!(isnanl (arg) || arg + arg == arg)) { \/* arg is finite and nonzero. *\/ int exponent = floorlog10l (arg < 0 ? -arg : arg); if (exponent >= 0 && tmp_length < exponent + precision) tmp_length = exponent + precision; } } # endif # if NEED_PRINTF_DOUBLE # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE if (type == TYPE_DOUBLE) # endif if (dp->conversion == 'f' || dp->conversion == 'F') { double arg = a.arg[dp->arg_index].a.a_double; if (!(isnand (arg) || arg + arg == arg)) { \/* arg is finite and nonzero. *\/ int exponent = floorlog10 (arg < 0 ? -arg : arg); if (exponent >= 0 && tmp_length < exponent + precision) tmp_length = exponent + precision; } } # endif \/* Account for sign, decimal point etc. *\/ tmp_length = xsum (tmp_length, 12); if (tmp_length < width) tmp_length = width; tmp_length = xsum (tmp_length, 1); \/* account for trailing NUL *\/ if (tmp_length <= sizeof (tmpbuf) \/ sizeof (DCHAR_T)) tmp = tmpbuf; else { size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T)); if (size_overflow_p (tmp_memsize)) \/* Overflow, would lead to out of memory. *\/ goto out_of_memory; tmp = (DCHAR_T *) malloc (tmp_memsize); if (tmp == NULL) \/* Out of memory. *\/ goto out_of_memory; } pad_ptr = NULL; p = tmp; # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE if (type == TYPE_LONGDOUBLE) # endif { long double arg = a.arg[dp->arg_index].a.a_longdouble; if (isnanl (arg)) { if (dp->conversion >= 'A' && dp->conversion <= 'Z') { *p++ = 'N'; *p++ = 'A'; *p++ = 'N'; } else { *p++ = 'n'; *p++ = 'a'; *p++ = 'n'; } } else { int sign = 0; DECL_LONG_DOUBLE_ROUNDING BEGIN_LONG_DOUBLE_ROUNDING (); if (signbit (arg)) \/* arg < 0.0L or negative zero *\/ { sign = -1; arg = -arg; } if (sign < 0) *p++ = '-'; else if (flags & FLAG_SHOWSIGN) *p++ = '+'; else if (flags & FLAG_SPACE) *p++ = ' '; if (arg > 0.0L && arg + arg == arg) { if (dp->conversion >= 'A' && dp->conversion <= 'Z') { *p++ = 'I'; *p++ = 'N'; *p++ = 'F'; } else { *p++ = 'i'; *p++ = 'n'; *p++ = 'f'; } } else { # if NEED_PRINTF_LONG_DOUBLE pad_ptr = p; if (dp->conversion == 'f' || dp->conversion == 'F') { char *digits; size_t ndigits; digits = scale10_round_decimal_long_double (arg, precision); if (digits == NULL) { END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } ndigits = strlen (digits); if (ndigits > precision) do { --ndigits; *p++ = digits[ndigits]; } while (ndigits > precision); else *p++ = '0'; \/* Here ndigits <= precision. *\/ if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > ndigits; precision--) *p++ = '0'; while (ndigits > 0) { --ndigits; *p++ = digits[ndigits]; } } free (digits); } else if (dp->conversion == 'e' || dp->conversion == 'E') { int exponent; if (arg == 0.0L) { exponent = 0; *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } } else { \/* arg > 0.0L. *\/ int adjusted; char *digits; size_t ndigits; exponent = floorlog10l (arg); adjusted = 0; for (;;) { digits = scale10_round_decimal_long_double (arg, (int)precision - exponent); if (digits == NULL) { END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } ndigits = strlen (digits); if (ndigits == precision + 1) break; if (ndigits < precision || ndigits > precision + 2) \/* The exponent was not guessed precisely enough. *\/ abort (); if (adjusted) \/* None of two values of exponent is the right one. Prevent an endless loop. *\/ abort (); free (digits); if (ndigits == precision) exponent -= 1; else exponent += 1; adjusted = 1; } \/* Here ndigits = precision+1. *\/ if (is_borderline (digits, precision)) { \/* Maybe the exponent guess was too high and a smaller exponent can be reached by turning a 10...0 into 9...9x. *\/ char *digits2 = scale10_round_decimal_long_double (arg, (int)precision - exponent + 1); if (digits2 == NULL) { free (digits); END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } if (strlen (digits2) == precision + 1) { free (digits); digits = digits2; exponent -= 1; } else free (digits2); } \/* Here ndigits = precision+1. *\/ *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); while (ndigits > 0) { --ndigits; *p++ = digits[ndigits]; } } free (digits); } *p++ = dp->conversion; \/* 'e' or 'E' *\/ # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = { '%', '+', '.', '2', 'd', '\\0' }; SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\\0') p++; # else if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, \"%+.2d\", exponent); while (*p != '\\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, \"%+.2d\", exponent); for (ep = expbuf; (*p = *ep) != '\\0'; ep++) p++; } # endif } else if (dp->conversion == 'g' || dp->conversion == 'G') { if (precision == 0) precision = 1; \/* precision >= 1. *\/ if (arg == 0.0L) \/* The exponent is 0, >= -4, < precision. Use fixed-point notation. *\/ { size_t ndigits = precision; \/* Number of trailing zeroes that have to be dropped. *\/ size_t nzeroes = (flags & FLAG_ALT ? 0 : precision - 1); --ndigits; *p++ = '0'; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = '0'; } } } else { \/* arg > 0.0L. *\/ int exponent; int adjusted; char *digits; size_t ndigits; size_t nzeroes; exponent = floorlog10l (arg); adjusted = 0; for (;;) { digits = scale10_round_decimal_long_double (arg, (int)(precision - 1) - exponent); if (digits == NULL) { END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } ndigits = strlen (digits); if (ndigits == precision) break; if (ndigits < precision - 1 || ndigits > precision + 1) \/* The exponent was not guessed precisely enough. *\/ abort (); if (adjusted) \/* None of two values of exponent is the right one. Prevent an endless loop. *\/ abort (); free (digits); if (ndigits < precision) exponent -= 1; else exponent += 1; adjusted = 1; } \/* Here ndigits = precision. *\/ if (is_borderline (digits, precision - 1)) { \/* Maybe the exponent guess was too high and a smaller exponent can be reached by turning a 10...0 into 9...9x. *\/ char *digits2 = scale10_round_decimal_long_double (arg, (int)(precision - 1) - exponent + 1); if (digits2 == NULL) { free (digits); END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } if (strlen (digits2) == precision) { free (digits); digits = digits2; exponent -= 1; } else free (digits2); } \/* Here ndigits = precision. *\/ \/* Determine the number of trailing zeroes that have to be dropped. *\/ nzeroes = 0; if ((flags & FLAG_ALT) == 0) while (nzeroes < ndigits && digits[nzeroes] == '0') nzeroes++; \/* The exponent is now determined. *\/ if (exponent >= -4 && exponent < (long)precision) { \/* Fixed-point notation: max(exponent,0)+1 digits, then the decimal point, then the remaining digits without trailing zeroes. *\/ if (exponent >= 0) { size_t ecount = exponent + 1; \/* Note: count <= precision = ndigits. *\/ for (; ecount > 0; ecount--) *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } } else { size_t ecount = -exponent - 1; *p++ = '0'; *p++ = decimal_point_char (); for (; ecount > 0; ecount--) *p++ = '0'; while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } } else { \/* Exponential notation. *\/ *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } *p++ = dp->conversion - 'G' + 'E'; \/* 'e' or 'E' *\/ # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = { '%', '+', '.', '2', 'd', '\\0' }; SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\\0') p++; # else if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, \"%+.2d\", exponent); while (*p != '\\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, \"%+.2d\", exponent); for (ep = expbuf; (*p = *ep) != '\\0'; ep++) p++; } # endif } free (digits); } } else abort (); # else \/* arg is finite. *\/ if (!(arg == 0.0L)) abort (); pad_ptr = p; if (dp->conversion == 'f' || dp->conversion == 'F') { *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } } else if (dp->conversion == 'e' || dp->conversion == 'E') { *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } *p++ = dp->conversion; \/* 'e' or 'E' *\/ *p++ = '+'; *p++ = '0'; *p++ = '0'; } else if (dp->conversion == 'g' || dp->conversion == 'G') { *p++ = '0'; if (flags & FLAG_ALT) { size_t ndigits = (precision > 0 ? precision - 1 : 0); *p++ = decimal_point_char (); for (; ndigits > 0; --ndigits) *p++ = '0'; } } else if (dp->conversion == 'a' || dp->conversion == 'A') { *p++ = '0'; *p++ = dp->conversion - 'A' + 'X'; pad_ptr = p; *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } *p++ = dp->conversion - 'A' + 'P'; *p++ = '+'; *p++ = '0'; } else abort (); # endif } END_LONG_DOUBLE_ROUNDING (); } } # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE else # endif # endif # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE { double arg = a.arg[dp->arg_index].a.a_double; if (isnand (arg)) { if (dp->conversion >= 'A' && dp->conversion <= 'Z') { *p++ = 'N'; *p++ = 'A'; *p++ = 'N'; } else { *p++ = 'n'; *p++ = 'a'; *p++ = 'n'; } } else { int sign = 0; if (signbit (arg)) \/* arg < 0.0 or negative zero *\/ { sign = -1; arg = -arg; } if (sign < 0) *p++ = '-'; else if (flags & FLAG_SHOWSIGN) *p++ = '+'; else if (flags & FLAG_SPACE) *p++ = ' '; if (arg > 0.0 && arg + arg == arg) { if (dp->conversion >= 'A' && dp->conversion <= 'Z') { *p++ = 'I'; *p++ = 'N'; *p++ = 'F'; } else { *p++ = 'i'; *p++ = 'n'; *p++ = 'f'; } } else { # if NEED_PRINTF_DOUBLE pad_ptr = p; if (dp->conversion == 'f' || dp->conversion == 'F') { char *digits; size_t ndigits; digits = scale10_round_decimal_double (arg, precision); if (digits == NULL) goto out_of_memory; ndigits = strlen (digits); if (ndigits > precision) do { --ndigits; *p++ = digits[ndigits]; } while (ndigits > precision); else *p++ = '0'; \/* Here ndigits <= precision. *\/ if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > ndigits; precision--) *p++ = '0'; while (ndigits > 0) { --ndigits; *p++ = digits[ndigits]; } } free (digits); } else if (dp->conversion == 'e' || dp->conversion == 'E') { int exponent; if (arg == 0.0) { exponent = 0; *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } } else { \/* arg > 0.0. *\/ int adjusted; char *digits; size_t ndigits; exponent = floorlog10 (arg); adjusted = 0; for (;;) { digits = scale10_round_decimal_double (arg, (int)precision - exponent); if (digits == NULL) goto out_of_memory; ndigits = strlen (digits); if (ndigits == precision + 1) break; if (ndigits < precision || ndigits > precision + 2) \/* The exponent was not guessed precisely enough. *\/ abort (); if (adjusted) \/* None of two values of exponent is the right one. Prevent an endless loop. *\/ abort (); free (digits); if (ndigits == precision) exponent -= 1; else exponent += 1; adjusted = 1; } \/* Here ndigits = precision+1. *\/ if (is_borderline (digits, precision)) { \/* Maybe the exponent guess was too high and a smaller exponent can be reached by turning a 10...0 into 9...9x. *\/ char *digits2 = scale10_round_decimal_double (arg, (int)precision - exponent + 1); if (digits2 == NULL) { free (digits); goto out_of_memory; } if (strlen (digits2) == precision + 1) { free (digits); digits = digits2; exponent -= 1; } else free (digits2); } \/* Here ndigits = precision+1. *\/ *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); while (ndigits > 0) { --ndigits; *p++ = digits[ndigits]; } } free (digits); } *p++ = dp->conversion; \/* 'e' or 'E' *\/ # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = \/* Produce the same number of exponent digits as the native printf implementation. *\/ # if defined _WIN32 && ! defined __CYGWIN__ { '%', '+', '.', '3', 'd', '\\0' }; # else { '%', '+', '.', '2', 'd', '\\0' }; # endif SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\\0') p++; # else { static const char decimal_format[] = \/* Produce the same number of exponent digits as the native printf implementation. *\/ # if defined _WIN32 && ! defined __CYGWIN__ \"%+.3d\"; # else \"%+.2d\"; # endif if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, decimal_format, exponent); while (*p != '\\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, decimal_format, exponent); for (ep = expbuf; (*p = *ep) != '\\0'; ep++) p++; } } # endif } else if (dp->conversion == 'g' || dp->conversion == 'G') { if (precision == 0) precision = 1; \/* precision >= 1. *\/ if (arg == 0.0) \/* The exponent is 0, >= -4, < precision. Use fixed-point notation. *\/ { size_t ndigits = precision; \/* Number of trailing zeroes that have to be dropped. *\/ size_t nzeroes = (flags & FLAG_ALT ? 0 : precision - 1); --ndigits; *p++ = '0'; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = '0'; } } } else { \/* arg > 0.0. *\/ int exponent; int adjusted; char *digits; size_t ndigits; size_t nzeroes; exponent = floorlog10 (arg); adjusted = 0; for (;;) { digits = scale10_round_decimal_double (arg, (int)(precision - 1) - exponent); if (digits == NULL) goto out_of_memory; ndigits = strlen (digits); if (ndigits == precision) break; if (ndigits < precision - 1 || ndigits > precision + 1) \/* The exponent was not guessed precisely enough. *\/ abort (); if (adjusted) \/* None of two values of exponent is the right one. Prevent an endless loop. *\/ abort (); free (digits); if (ndigits < precision) exponent -= 1; else exponent += 1; adjusted = 1; } \/* Here ndigits = precision. *\/ if (is_borderline (digits, precision - 1)) { \/* Maybe the exponent guess was too high and a smaller exponent can be reached by turning a 10...0 into 9...9x. *\/ char *digits2 = scale10_round_decimal_double (arg, (int)(precision - 1) - exponent + 1); if (digits2 == NULL) { free (digits); goto out_of_memory; } if (strlen (digits2) == precision) { free (digits); digits = digits2; exponent -= 1; } else free (digits2); } \/* Here ndigits = precision. *\/ \/* Determine the number of trailing zeroes that have to be dropped. *\/ nzeroes = 0; if ((flags & FLAG_ALT) == 0) while (nzeroes < ndigits && digits[nzeroes] == '0') nzeroes++; \/* The exponent is now determined. *\/ if (exponent >= -4 && exponent < (long)precision) { \/* Fixed-point notation: max(exponent,0)+1 digits, then the decimal point, then the remaining digits without trailing zeroes. *\/ if (exponent >= 0) { size_t ecount = exponent + 1; \/* Note: ecount <= precision = ndigits. *\/ for (; ecount > 0; ecount--) *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } } else { size_t ecount = -exponent - 1; *p++ = '0'; *p++ = decimal_point_char (); for (; ecount > 0; ecount--) *p++ = '0'; while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } } else { \/* Exponential notation. *\/ *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } *p++ = dp->conversion - 'G' + 'E'; \/* 'e' or 'E' *\/ # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = \/* Produce the same number of exponent digits as the native printf implementation. *\/ # if defined _WIN32 && ! defined __CYGWIN__ { '%', '+', '.', '3', 'd', '\\0' }; # else { '%', '+', '.', '2', 'd', '\\0' }; # endif SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\\0') p++; # else { static const char decimal_format[] = \/* Produce the same number of exponent digits as the native printf implementation. *\/ # if defined _WIN32 && ! defined __CYGWIN__ \"%+.3d\"; # else \"%+.2d\"; # endif if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, decimal_format, exponent); while (*p != '\\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, decimal_format, exponent); for (ep = expbuf; (*p = *ep) != '\\0'; ep++) p++; } } # endif } free (digits); } } else abort (); # else \/* arg is finite. *\/ if (!(arg == 0.0)) abort (); pad_ptr = p; if (dp->conversion == 'f' || dp->conversion == 'F') { *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } } else if (dp->conversion == 'e' || dp->conversion == 'E') { *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } *p++ = dp->conversion; \/* 'e' or 'E' *\/ *p++ = '+'; \/* Produce the same number of exponent digits as the native printf implementation. *\/ # if defined _WIN32 && ! defined __CYGWIN__ *p++ = '0'; # endif *p++ = '0'; *p++ = '0'; } else if (dp->conversion == 'g' || dp->conversion == 'G') { *p++ = '0'; if (flags & FLAG_ALT) { size_t ndigits = (precision > 0 ? precision - 1 : 0); *p++ = decimal_point_char (); for (; ndigits > 0; --ndigits) *p++ = '0'; } } else abort (); # endif } } } # endif \/* The generated string now extends from tmp to p, with the zero padding insertion point being at pad_ptr. *\/ count = p - tmp; if (count < width) { size_t pad = width - count; DCHAR_T *end = p + pad; if (flags & FLAG_LEFT) { \/* Pad with spaces on the right. *\/ for (; pad > 0; pad--) *p++ = ' '; } else if ((flags & FLAG_ZERO) && pad_ptr != NULL) { \/* Pad with zeroes. *\/ DCHAR_T *q = end; while (p > pad_ptr) *--q = *--p; for (; pad > 0; pad--) *p++ = '0'; } else { \/* Pad with spaces on the left. *\/ DCHAR_T *q = end; while (p > tmp) *--q = *--p; for (; pad > 0; pad--) *p++ = ' '; } p = end; } count = p - tmp; if (count >= tmp_length) \/* tmp_length was incorrectly calculated - fix the code above! *\/ abort (); \/* Make room for the result. *\/ if (count >= allocated - length) { size_t n = xsum (length, count); ENSURE_ALLOCATION (n); } \/* Append the result. *\/ memcpy (result + length, tmp, count * sizeof (DCHAR_T)); if (tmp != tmpbuf) free (tmp); length += count; } #endif else { arg_type type = a.arg[dp->arg_index].type; int flags = dp->flags; #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION int has_width; #endif #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION size_t width; #endif #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION int has_precision; size_t precision; #endif #if NEED_PRINTF_UNBOUNDED_PRECISION int prec_ourselves; #else # define prec_ourselves 0 #endif #if NEED_PRINTF_FLAG_LEFTADJUST # define pad_ourselves 1 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION int pad_ourselves; #else # define pad_ourselves 0 #endif TCHAR_T *fbp; unsigned int prefix_count; int prefixes[2] IF_LINT (= { 0 }); int orig_errno; #if !USE_SNPRINTF size_t tmp_length; TCHAR_T tmpbuf[700]; TCHAR_T *tmp; #endif #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION has_width = 0; #endif #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { \/* \"A negative field width is taken as a '-' flag followed by a positive field width.\" *\/ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION has_width = 1; #endif } #endif #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION has_precision = 0; precision = 6; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; \/* \"A negative precision is taken as if the precision were omitted.\" *\/ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } #endif \/* Decide whether to handle the precision ourselves. *\/ #if NEED_PRINTF_UNBOUNDED_PRECISION switch (dp->conversion) { case 'd': case 'i': case 'u': case 'o': case 'x': case 'X': case 'p': prec_ourselves = has_precision && (precision > 0); break; default: prec_ourselves = 0; break; } #endif \/* Decide whether to perform the padding ourselves. *\/ #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION) switch (dp->conversion) { # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO \/* If we need conversion from TCHAR_T[] to DCHAR_T[], we need to perform the padding after this conversion. Functions with unistdio extensions perform the padding based on character count rather than element count. *\/ case 'c': case 's': # endif # if NEED_PRINTF_FLAG_ZERO case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': case 'a': case 'A': # endif pad_ourselves = 1; break; default: pad_ourselves = prec_ourselves; break; } #endif #if !USE_SNPRINTF \/* Allocate a temporary buffer of sufficient size for calling sprintf. *\/ tmp_length = MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type, flags, width, has_precision, precision, pad_ourselves); if (tmp_length <= sizeof (tmpbuf) \/ sizeof (TCHAR_T)) tmp = tmpbuf; else { size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T)); if (size_overflow_p (tmp_memsize)) \/* Overflow, would lead to out of memory. *\/ goto out_of_memory; tmp = (TCHAR_T *) malloc (tmp_memsize); if (tmp == NULL) \/* Out of memory. *\/ goto out_of_memory; } #endif \/* Construct the format string for calling snprintf or sprintf. *\/ fbp = buf; *fbp++ = '%'; #if NEED_PRINTF_FLAG_GROUPING \/* The underlying implementation doesn't support the ' flag. Produce no grouping characters in this case; this is acceptable because the grouping is locale dependent. *\/ #else if (flags & FLAG_GROUP) *fbp++ = '\\''; #endif if (flags & FLAG_LEFT) *fbp++ = '-'; if (flags & FLAG_SHOWSIGN) *fbp++ = '+'; if (flags & FLAG_SPACE) *fbp++ = ' '; if (flags & FLAG_ALT) *fbp++ = '#'; #if __GLIBC__ >= 2 && !defined __UCLIBC__ if (flags & FLAG_LOCALIZED) *fbp++ = 'I'; #endif if (!pad_ourselves) { if (flags & FLAG_ZERO) *fbp++ = '0'; if (dp->width_start != dp->width_end) { size_t n = dp->width_end - dp->width_start; \/* The width specification is known to consist only of standard ASCII characters. *\/ if (sizeof (FCHAR_T) == sizeof (TCHAR_T)) { memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T)); fbp += n; } else { const FCHAR_T *mp = dp->width_start; do *fbp++ = *mp++; while (--n > 0); } } } if (!prec_ourselves) { if (dp->precision_start != dp->precision_end) { size_t n = dp->precision_end - dp->precision_start; \/* The precision specification is known to consist only of standard ASCII characters. *\/ if (sizeof (FCHAR_T) == sizeof (TCHAR_T)) { memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T)); fbp += n; } else { const FCHAR_T *mp = dp->precision_start; do *fbp++ = *mp++; while (--n > 0); } } } switch (type) { #if HAVE_LONG_LONG_INT case TYPE_LONGLONGINT: case TYPE_ULONGLONGINT: # if defined _WIN32 && ! defined __CYGWIN__ *fbp++ = 'I'; *fbp++ = '6'; *fbp++ = '4'; break; # else *fbp++ = 'l'; # endif #endif FALLTHROUGH; case TYPE_LONGINT: case TYPE_ULONGINT: #if HAVE_WINT_T case TYPE_WIDE_CHAR: #endif #if HAVE_WCHAR_T case TYPE_WIDE_STRING: #endif *fbp++ = 'l'; break; case TYPE_LONGDOUBLE: *fbp++ = 'L'; break; default: break; } #if NEED_PRINTF_DIRECTIVE_F if (dp->conversion == 'F') *fbp = 'f'; else #endif *fbp = dp->conversion; #if USE_SNPRINTF # if ! (((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) \\ && !defined __UCLIBC__) \\ || (defined __APPLE__ && defined __MACH__) \\ || (defined _WIN32 && ! defined __CYGWIN__)) fbp[1] = '%'; fbp[2] = 'n'; fbp[3] = '\\0'; # else \/* On glibc2 systems from glibc >= 2.3 - probably also older ones - we know that snprintf's return value conforms to ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and gl_SNPRINTF_TRUNCATION_C99 pass. Therefore we can avoid using %n in this situation. On glibc2 systems from 2004-10-18 or newer, the use of %n in format strings in writable memory may crash the program (if compiled with _FORTIFY_SOURCE=2), so we should avoid it in this situation. *\/ \/* On Mac OS X 10.3 or newer, we know that snprintf's return value conforms to ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and gl_SNPRINTF_TRUNCATION_C99 pass. Therefore we can avoid using %n in this situation. On Mac OS X 10.13 or newer, the use of %n in format strings in writable memory by default crashes the program, so we should avoid it in this situation. *\/ \/* On native Windows systems (such as mingw), we can avoid using %n because: - Although the gl_SNPRINTF_TRUNCATION_C99 test fails, snprintf does not write more than the specified number of bytes. (snprintf (buf, 3, \"%d %d\", 4567, 89) writes '4', '5', '6' into buf, not '4', '5', '\\0'.) - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf allows us to recognize the case of an insufficient buffer size: it returns -1 in this case. On native Windows systems (such as mingw) where the OS is Windows Vista, the use of %n in format strings by default crashes the program. See and So we should avoid %n in this situation. *\/ fbp[1] = '\\0'; # endif #else fbp[1] = '\\0'; #endif \/* Construct the arguments for calling snprintf or sprintf. *\/ prefix_count = 0; if (!pad_ourselves && dp->width_arg_index != ARG_NONE) { if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int; } if (!prec_ourselves && dp->precision_arg_index != ARG_NONE) { if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int; } #if USE_SNPRINTF \/* The SNPRINTF result is appended after result[0..length]. The latter is an array of DCHAR_T; SNPRINTF appends an array of TCHAR_T to it. This is possible because sizeof (TCHAR_T) divides sizeof (DCHAR_T) and alignof (TCHAR_T) <= alignof (DCHAR_T). *\/ # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) \/ sizeof (TCHAR_T)) \/* Ensure that maxlen below will be >= 2. Needed on BeOS, where an snprintf() with maxlen==1 acts like sprintf(). *\/ ENSURE_ALLOCATION (xsum (length, (2 + TCHARS_PER_DCHAR - 1) \/ TCHARS_PER_DCHAR)); \/* Prepare checking whether snprintf returns the count via %n. *\/ *(TCHAR_T *) (result + length) = '\\0'; #endif orig_errno = errno; for (;;) { int count = -1; #if USE_SNPRINTF int retcount = 0; size_t maxlen = allocated - length; \/* SNPRINTF can fail if its second argument is > INT_MAX. *\/ if (maxlen > INT_MAX \/ TCHARS_PER_DCHAR) maxlen = INT_MAX \/ TCHARS_PER_DCHAR; maxlen = maxlen * TCHARS_PER_DCHAR; # define SNPRINTF_BUF(arg) \\ switch (prefix_count) \\ { \\ case 0: \\ retcount = SNPRINTF ((TCHAR_T *) (result + length), \\ maxlen, buf, \\ arg, &count); \\ break; \\ case 1: \\ retcount = SNPRINTF ((TCHAR_T *) (result + length), \\ maxlen, buf, \\ prefixes[0], arg, &count); \\ break; \\ case 2: \\ retcount = SNPRINTF ((TCHAR_T *) (result + length), \\ maxlen, buf, \\ prefixes[0], prefixes[1], arg, \\ &count); \\ break; \\ default: \\ abort (); \\ } #else # define SNPRINTF_BUF(arg) \\ switch (prefix_count) \\ { \\ case 0: \\ count = sprintf (tmp, buf, arg); \\ break; \\ case 1: \\ count = sprintf (tmp, buf, prefixes[0], arg); \\ break; \\ case 2: \\ count = sprintf (tmp, buf, prefixes[0], prefixes[1],\\ arg); \\ break; \\ default: \\ abort (); \\ } #endif errno = 0; switch (type) { case TYPE_SCHAR: { int arg = a.arg[dp->arg_index].a.a_schar; SNPRINTF_BUF (arg); } break; case TYPE_UCHAR: { unsigned int arg = a.arg[dp->arg_index].a.a_uchar; SNPRINTF_BUF (arg); } break; case TYPE_SHORT: { int arg = a.arg[dp->arg_index].a.a_short; SNPRINTF_BUF (arg); } break; case TYPE_USHORT: { unsigned int arg = a.arg[dp->arg_index].a.a_ushort; SNPRINTF_BUF (arg); } break; case TYPE_INT: { int arg = a.arg[dp->arg_index].a.a_int; SNPRINTF_BUF (arg); } break; case TYPE_UINT: { unsigned int arg = a.arg[dp->arg_index].a.a_uint; SNPRINTF_BUF (arg); } break; case TYPE_LONGINT: { long int arg = a.arg[dp->arg_index].a.a_longint; SNPRINTF_BUF (arg); } break; case TYPE_ULONGINT: { unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint; SNPRINTF_BUF (arg); } break; #if HAVE_LONG_LONG_INT case TYPE_LONGLONGINT: { long long int arg = a.arg[dp->arg_index].a.a_longlongint; SNPRINTF_BUF (arg); } break; case TYPE_ULONGLONGINT: { unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint; SNPRINTF_BUF (arg); } break; #endif case TYPE_DOUBLE: { double arg = a.arg[dp->arg_index].a.a_double; SNPRINTF_BUF (arg); } break; case TYPE_LONGDOUBLE: { long double arg = a.arg[dp->arg_index].a.a_longdouble; SNPRINTF_BUF (arg); } break; case TYPE_CHAR: { int arg = a.arg[dp->arg_index].a.a_char; SNPRINTF_BUF (arg); } break; #if HAVE_WINT_T case TYPE_WIDE_CHAR: { wint_t arg = a.arg[dp->arg_index].a.a_wide_char; SNPRINTF_BUF (arg); } break; #endif case TYPE_STRING: { const char *arg = a.arg[dp->arg_index].a.a_string; SNPRINTF_BUF (arg); } break; #if HAVE_WCHAR_T case TYPE_WIDE_STRING: { const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string; SNPRINTF_BUF (arg); } break; #endif case TYPE_POINTER: { void *arg = a.arg[dp->arg_index].a.a_pointer; SNPRINTF_BUF (arg); } break; default: abort (); } #if USE_SNPRINTF \/* Portability: Not all implementations of snprintf() are ISO C 99 compliant. Determine the number of bytes that snprintf() has produced or would have produced. *\/ if (count >= 0) { \/* Verify that snprintf() has NUL-terminated its result. *\/ if (count < maxlen && ((TCHAR_T *) (result + length)) [count] != '\\0') abort (); \/* Portability hack. *\/ if (retcount > count) count = retcount; } else { \/* snprintf() doesn't understand the '%n' directive. *\/ if (fbp[1] != '\\0') { \/* Don't use the '%n' directive; instead, look at the snprintf() return value. *\/ fbp[1] = '\\0'; continue; } else { \/* Look at the snprintf() return value. *\/ if (retcount < 0) { # if !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF \/* HP-UX 10.20 snprintf() is doubly deficient: It doesn't understand the '%n' directive, *and* it returns -1 (rather than the length that would have been required) when the buffer is too small. But a failure at this point can also come from other reasons than a too small buffer, such as an invalid wide string argument to the %ls directive, or possibly an invalid floating-point argument. *\/ size_t tmp_length = MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type, flags, width, has_precision, precision, pad_ourselves); if (maxlen < tmp_length) { \/* Make more room. But try to do through this reallocation only once. *\/ size_t bigger_need = xsum (length, xsum (tmp_length, TCHARS_PER_DCHAR - 1) \/ TCHARS_PER_DCHAR); \/* And always grow proportionally. (There may be several arguments, each needing a little more room than the previous one.) *\/ size_t bigger_need2 = xsum (xtimes (allocated, 2), 12); if (bigger_need < bigger_need2) bigger_need = bigger_need2; ENSURE_ALLOCATION (bigger_need); continue; } # endif } else count = retcount; } } #endif \/* Attempt to handle failure. *\/ if (count < 0) { \/* SNPRINTF or sprintf failed. Save and use the errno that it has set, if any. *\/ int saved_errno = errno; if (saved_errno == 0) { if (dp->conversion == 'c' || dp->conversion == 's') saved_errno = EILSEQ; else saved_errno = EINVAL; } if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } #if USE_SNPRINTF \/* Handle overflow of the allocated buffer. If such an overflow occurs, a C99 compliant snprintf() returns a count >= maxlen. However, a non-compliant snprintf() function returns only count = maxlen - 1. To cover both cases, test whether count >= maxlen - 1. *\/ if ((unsigned int) count + 1 >= maxlen) { \/* If maxlen already has attained its allowed maximum, allocating more memory will not increase maxlen. Instead of looping, bail out. *\/ if (maxlen == INT_MAX \/ TCHARS_PER_DCHAR) goto overflow; else { \/* Need at least (count + 1) * sizeof (TCHAR_T) bytes. (The +1 is for the trailing NUL.) But ask for (count + 2) * sizeof (TCHAR_T) bytes, so that in the next round, we likely get maxlen > (unsigned int) count + 1 and so we don't get here again. And allocate proportionally, to avoid looping eternally if snprintf() reports a too small count. *\/ size_t n = xmax (xsum (length, ((unsigned int) count + 2 + TCHARS_PER_DCHAR - 1) \/ TCHARS_PER_DCHAR), xtimes (allocated, 2)); ENSURE_ALLOCATION (n); continue; } } #endif #if NEED_PRINTF_UNBOUNDED_PRECISION if (prec_ourselves) { \/* Handle the precision. *\/ TCHAR_T *prec_ptr = # if USE_SNPRINTF (TCHAR_T *) (result + length); # else tmp; # endif size_t prefix_count; size_t move; prefix_count = 0; \/* Put the additional zeroes after the sign. *\/ if (count >= 1 && (*prec_ptr == '-' || *prec_ptr == '+' || *prec_ptr == ' ')) prefix_count = 1; \/* Put the additional zeroes after the 0x prefix if (flags & FLAG_ALT) || (dp->conversion == 'p'). *\/ else if (count >= 2 && prec_ptr[0] == '0' && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X')) prefix_count = 2; move = count - prefix_count; if (precision > move) { \/* Insert zeroes. *\/ size_t insert = precision - move; TCHAR_T *prec_end; # if USE_SNPRINTF size_t n = xsum (length, (count + insert + TCHARS_PER_DCHAR - 1) \/ TCHARS_PER_DCHAR); length += (count + TCHARS_PER_DCHAR - 1) \/ TCHARS_PER_DCHAR; ENSURE_ALLOCATION (n); length -= (count + TCHARS_PER_DCHAR - 1) \/ TCHARS_PER_DCHAR; prec_ptr = (TCHAR_T *) (result + length); # endif prec_end = prec_ptr + count; prec_ptr += prefix_count; while (prec_end > prec_ptr) { prec_end--; prec_end[insert] = prec_end[0]; } prec_end += insert; do *--prec_end = '0'; while (prec_end > prec_ptr); count += insert; } } #endif #if !USE_SNPRINTF if (count >= tmp_length) \/* tmp_length was incorrectly calculated - fix the code above! *\/ abort (); #endif #if !DCHAR_IS_TCHAR \/* Convert from TCHAR_T[] to DCHAR_T[]. *\/ if (dp->conversion == 'c' || dp->conversion == 's') { \/* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING TYPE_WIDE_STRING. The result string is not certainly ASCII. *\/ const TCHAR_T *tmpsrc; DCHAR_T *tmpdst; size_t tmpdst_len; \/* This code assumes that TCHAR_T is 'char'. *\/ verify (sizeof (TCHAR_T) == 1); # if USE_SNPRINTF tmpsrc = (TCHAR_T *) (result + length); # else tmpsrc = tmp; # endif tmpdst = DCHAR_CONV_FROM_ENCODING (locale_charset (), iconveh_question_mark, tmpsrc, count, NULL, NULL, &tmpdst_len); if (tmpdst == NULL) { int saved_errno = errno; if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } ENSURE_ALLOCATION (xsum (length, tmpdst_len)); DCHAR_CPY (result + length, tmpdst, tmpdst_len); free (tmpdst); count = tmpdst_len; } else { \/* The result string is ASCII. Simple 1:1 conversion. *\/ # if USE_SNPRINTF \/* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a no-op conversion, in-place on the array starting at (result + length). *\/ if (sizeof (DCHAR_T) != sizeof (TCHAR_T)) # endif { const TCHAR_T *tmpsrc; DCHAR_T *tmpdst; size_t n; # if USE_SNPRINTF if (result == resultbuf) { tmpsrc = (TCHAR_T *) (result + length); \/* ENSURE_ALLOCATION will not move tmpsrc (because it's part of resultbuf). *\/ ENSURE_ALLOCATION (xsum (length, count)); } else { \/* ENSURE_ALLOCATION will move the array (because it uses realloc(). *\/ ENSURE_ALLOCATION (xsum (length, count)); tmpsrc = (TCHAR_T *) (result + length); } # else tmpsrc = tmp; ENSURE_ALLOCATION (xsum (length, count)); # endif tmpdst = result + length; \/* Copy backwards, because of overlapping. *\/ tmpsrc += count; tmpdst += count; for (n = count; n > 0; n--) *--tmpdst = *--tmpsrc; } } #endif #if DCHAR_IS_TCHAR && !USE_SNPRINTF \/* Make room for the result. *\/ if (count > allocated - length) { \/* Need at least count elements. But allocate proportionally. *\/ size_t n = xmax (xsum (length, count), xtimes (allocated, 2)); ENSURE_ALLOCATION (n); } #endif \/* Here count <= allocated - length. *\/ \/* Perform padding. *\/ #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION if (pad_ourselves && has_width) { size_t w; # if ENABLE_UNISTDIO \/* Outside POSIX, it's preferable to compare the width against the number of _characters_ of the converted value. *\/ w = DCHAR_MBSNLEN (result + length, count); # else \/* The width is compared against the number of _bytes_ of the converted value, says POSIX. *\/ w = count; # endif if (w < width) { size_t pad = width - w; \/* Make room for the result. *\/ if (xsum (count, pad) > allocated - length) { \/* Need at least count + pad elements. But allocate proportionally. *\/ size_t n = xmax (xsum3 (length, count, pad), xtimes (allocated, 2)); # if USE_SNPRINTF length += count; ENSURE_ALLOCATION (n); length -= count; # else ENSURE_ALLOCATION (n); # endif } \/* Here count + pad <= allocated - length. *\/ { # if !DCHAR_IS_TCHAR || USE_SNPRINTF DCHAR_T * const rp = result + length; # else DCHAR_T * const rp = tmp; # endif DCHAR_T *p = rp + count; DCHAR_T *end = p + pad; DCHAR_T *pad_ptr; # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO if (dp->conversion == 'c' || dp->conversion == 's') \/* No zero-padding for string directives. *\/ pad_ptr = NULL; else # endif { pad_ptr = (*rp == '-' ? rp + 1 : rp); \/* No zero-padding of \"inf\" and \"nan\". *\/ if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z') || (*pad_ptr >= 'a' && *pad_ptr <= 'z')) pad_ptr = NULL; } \/* The generated string now extends from rp to p, with the zero padding insertion point being at pad_ptr. *\/ count = count + pad; \/* = end - rp *\/ if (flags & FLAG_LEFT) { \/* Pad with spaces on the right. *\/ for (; pad > 0; pad--) *p++ = ' '; } else if ((flags & FLAG_ZERO) && pad_ptr != NULL) { \/* Pad with zeroes. *\/ DCHAR_T *q = end; while (p > pad_ptr) *--q = *--p; for (; pad > 0; pad--) *p++ = '0'; } else { \/* Pad with spaces on the left. *\/ DCHAR_T *q = end; while (p > rp) *--q = *--p; for (; pad > 0; pad--) *p++ = ' '; } } } } #endif \/* Here still count <= allocated - length. *\/ #if !DCHAR_IS_TCHAR || USE_SNPRINTF \/* The snprintf() result did fit. *\/ #else \/* Append the sprintf() result. *\/ memcpy (result + length, tmp, count * sizeof (DCHAR_T)); #endif #if !USE_SNPRINTF if (tmp != tmpbuf) free (tmp); #endif #if NEED_PRINTF_DIRECTIVE_F if (dp->conversion == 'F') { \/* Convert the %f result to upper case for %F. *\/ DCHAR_T *rp = result + length; size_t rc; for (rc = count; rc > 0; rc--, rp++) if (*rp >= 'a' && *rp <= 'z') *rp = *rp - 'a' + 'A'; } #endif length += count; break; } errno = orig_errno; #undef pad_ourselves #undef prec_ourselves } } } \/* Add the final NUL. *\/ ENSURE_ALLOCATION (xsum (length, 1)); result[length] = '\\0'; if (result != resultbuf && length + 1 < allocated) { \/* Shrink the allocated memory if possible. *\/ DCHAR_T *memory; memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T)); if (memory != NULL) result = memory; } if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); *lengthp = length; \/* Note that we can produce a big string of a length > INT_MAX. POSIX says that snprintf() fails with errno = EOVERFLOW in this case, but that's only because snprintf() returns an 'int'. This function does not have this limitation. *\/ return result; #if USE_SNPRINTF overflow: if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EOVERFLOW; return NULL; #endif out_of_memory: if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); out_of_memory_1: CLEANUP (); errno = ENOMEM; return NULL; } }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":64625,"input":"static MagickBooleanType SetsRGBImageProfile(Image *image) { static unsigned char sRGBProfile[] = { 0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, 0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a, 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99, 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67, 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88, 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c, 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24, 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24, 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14, 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14, 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14, 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d, 0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00, 0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c, 0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2, 0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d, 0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0, 0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87, 0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20, 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24, 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40, 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76, 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4, 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d, 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae, 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a, 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff, 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce, 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7, 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba, 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8, 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10, 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff }; StringInfo *profile; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (GetImageProfile(image,\"icc\") != (const StringInfo *) NULL) return(MagickFalse); profile=AcquireStringInfo(sizeof(sRGBProfile)); SetStringInfoDatum(profile,sRGBProfile); status=SetImageProfile(image,\"icc\",profile); profile=DestroyStringInfo(profile); return(status); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":206207,"input":"static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define CFormat \"\/Filter [ \/%s ]\\n\" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \\ { \\ if (xref != (MagickOffsetType *) NULL) \\ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \\ ThrowWriterException((exception),(message)); \\ } DisableMSCWarning(4310) static const char XMPProfile[]= { \"\\n\" \"\\n\" \" \\n\" \" \\n\" \" %s<\/xap:ModifyDate>\\n\" \" %s<\/xap:CreateDate>\\n\" \" %s<\/xap:MetadataDate>\\n\" \" %s<\/xap:CreatorTool>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" application\/pdf<\/dc:format>\\n\" \" \\n\" \" \\n\" \" %s<\/rdf:li>\\n\" \" <\/rdf:Alt>\\n\" \" <\/dc:title>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf<\/xapMM:DocumentID>\\n\" \" uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb<\/xapMM:InstanceID>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" %s<\/pdf:Producer>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" 3<\/pdfaid:part>\\n\" \" B<\/pdfaid:conformance>\\n\" \" <\/rdf:Description>\\n\" \" <\/rdf:RDF>\\n\" \"<\/x:xmpmeta>\\n\" \"\\n\" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MagickPathExtent], buffer[MagickPathExtent], *escape, date[MagickPathExtent], **labels, page_geometry[MagickPathExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm utc_time; time_t seconds; unsigned char *pixels; \/* Open output image file. *\/ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); \/* Allocate X ref memory. *\/ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(xref,0,2048UL*sizeof(*xref)); \/* Write Info object. *\/ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->alpha_trait != UndefinedPixelTrait) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,\"icc\"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\\n'); } \/* Write Catalog object. *\/ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Pages %.20g 0 R\\n\", (double) object+1); else { (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Metadata %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Pages %.20g 0 R\\n\", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Type \/Catalog\"); option=GetImageOption(image_info,\"pdf:page-direction\"); if ((option != (const char *) NULL) && (LocaleCompare(option,\"right-to-left\") == 0)) (void) WriteBlobString(image,\"\/ViewerPreferences<<\/PageDirection\/R2L>>\\n\"); (void) WriteBlobString(image,\"\\n\"); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { char create_date[MagickPathExtent], modify_date[MagickPathExtent], timestamp[MagickPathExtent], xmp_profile[MagickPathExtent]; \/* Write XMP object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Subtype \/XML\\n\"); *modify_date='\\0'; value=GetImageProperty(image,\"date:modify\",exception); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MagickPathExtent); *create_date='\\0'; value=GetImageProperty(image,\"date:create\",exception); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MagickPathExtent); (void) FormatMagickTime(GetMagickTime(),MagickPathExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g\\n\", (double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Type \/Metadata\\n\"); (void) WriteBlobString(image,\">>\\nstream\\n\"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); } \/* Write Pages object. *\/ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/Pages\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Kids [ %.20g 0 R \", (double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; \/* Predict page object id's. *\/ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,\"icc\"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } (void) WriteBlobString(image,\"]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Count %.20g\\n\",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,\"icc\"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,exception) == MagickFalse) || (image->alpha_trait != UndefinedPixelTrait)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; \/* LZW compression is forbidden *\/ break; } case NoCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; \/* ASCII 85 compression is forbidden *\/ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Scale relative to dots-per-inch. *\/ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)\/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)\/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,\"PDF\") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry, MagickPathExtent); (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)\/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)\/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; \/* Write Page object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/Page\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Parent %.20g 0 R\\n\", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Resources <<\\n\"); labels=(char **) NULL; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent, \"\/Font << \/F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent, \"\/XObject << \/Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ProcSet %.20g 0 R >>\\n\", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width\/resolution.x, 72.0*media_info.height\/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/CropBox [0 0 %g %g]\\n\",72.0*media_info.width\/resolution.x, 72.0*media_info.height\/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Contents %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Thumb %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Contents object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); (void) WriteBlobString(image,\"q\\n\"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,\"BT\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/F%.20g %g Tf\\n\", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\", labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"ET\\n\"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MagickPathExtent, \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x, (double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Im%.20g Do\\n\",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"Q\\n\"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Procset object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageC\",MagickPathExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageB\",MagickPathExtent); else (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageI\",MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\" ]\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Font object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (labels != (char **) NULL) { (void) WriteBlobString(image,\"\/Type \/Font\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Type1\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/F%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/BaseFont \/Helvetica\\n\"); (void) WriteBlobString(image,\"\/Encoding \/MacRomanEncoding\\n\"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write XObject object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/XObject\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/Im%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"\/Filter [ \/CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/DecodeParms [ << \" \"\/K %s \/BlackIs1 false \/Columns %.20g \/Rows %.20g >> ]\\n\",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ColorSpace %.20g 0 R\\n\", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->alpha_trait != UndefinedPixelTrait) { (void) FormatLocaleString(buffer,MagickPathExtent,\"\/SMask %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runoffset encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed DirectColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { \/* Dump number of colors and colormap. *\/ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Colorspace object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); device=\"DeviceRGB\"; channels=0; if (image->colorspace == CMYKColorspace) { device=\"DeviceCMYK\"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { device=\"DeviceGray\"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device=\"DeviceRGB\"; channels=3; } profile=GetImageProfile(image,\"icc\"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"\/%s\\n\",device); else (void) FormatLocaleString(buffer,MagickPathExtent, \"[ \/Indexed \/%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; \/* Write ICC profile. *\/ (void) FormatLocaleString(buffer,MagickPathExtent, \"[\/ICCBased %.20g 0 R]\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n\/N %.20g\\n\" \"\/Filter \/ASCII85Decode\\n\/Length %.20g 0 R\\n\/Alternate \/%s\\n>>\\n\" \"stream\\n\",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"endstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Thumb object. *\/ SetGeometry(image,&geometry); (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception); if (tile_image == (Image *) NULL) return(MagickFalse); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"\/Filter [ \/CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/DecodeParms [ << \" \"\/K %s \/BlackIs1 false \/Columns %.20g \/Rows %.20g >> ]\\n\",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ColorSpace %.20g 0 R\\n\", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image, exception); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( tile_image,p))); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed DirectColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(tile_image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(tile_image,p))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } else { \/* Dump number of colors and colormap. *\/ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, \"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=(unsigned char) GetPixelIndex(tile_image,p); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,(unsigned char) ((ssize_t) GetPixelIndex(tile_image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,\">>\\n\"); else { \/* Write Colormap object. *\/ if (compression == NoCompression) (void) WriteBlobString(image,\"\/Filter [ \/ASCII85Decode ]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); continue; } (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write softmask object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (image->alpha_trait == UndefinedPixelTrait) (void) WriteBlobString(image,\">>\\n\"); else { (void) WriteBlobString(image,\"\/Type \/XObject\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/Ma%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\", (double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/ColorSpace \/DeviceGray\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/BitsPerComponent %d\\n\",(compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); \/* Write Metadata object. *\/ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { escape=EscapeParenthesis(basename); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Title (%s)\\n\", escape); escape=DestroyString(escape); } else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { unsigned char hex_digits[16]; hex_digits[0]='0'; hex_digits[1]='1'; hex_digits[2]='2'; hex_digits[3]='3'; hex_digits[4]='4'; hex_digits[5]='5'; hex_digits[6]='6'; hex_digits[7]='7'; hex_digits[8]='8'; hex_digits[9]='9'; hex_digits[10]='A'; hex_digits[11]='B'; hex_digits[12]='C'; hex_digits[13]='D'; hex_digits[14]='E'; hex_digits[15]='F'; (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Title > 4) & 0x0f]); (void) WriteBlobByte(image,hex_digits[utf16[i] & 0x0f]); } (void) FormatLocaleString(buffer,MagickPathExtent,\">\\n\"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=GetMagickTime(); GetMagickUTCtime(&seconds,&utc_time); (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\", utc_time.tm_year+1900,utc_time.tm_mon+1,utc_time.tm_mday, utc_time.tm_hour,utc_time.tm_min,utc_time.tm_sec); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/CreationDate (%s)\\n\", date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ModDate (%s)\\n\",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Producer (%s)\\n\",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Xref object. *\/ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,\"xref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"0000000000 65535 f \\n\"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"trailer\\n\"); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Size %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Info %.20g 0 R\\n\",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Root %.20g 0 R\\n\",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image,exception); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ID [<%s> <%s>]\\n\", GetImageProperty(image,\"signature\",exception), GetImageProperty(image,\"signature\",exception)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"startxref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"%%EOF\\n\"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }","output":{"is_vulnerable":"True","vulnerability_types":["Integer Overflow or Wraparound"],"explanation":"In RestoreMSCWarning() of \/coders\/pdf.c there are several areas where calls to GetPixelIndex() could result in values outside the range of representable for the unsigned char type. The patch casts the return value of GetPixelIndex() to ssize_t type to avoid this bug. This undefined behavior could be triggered when ImageMagick processes a crafted pdf file. Red Hat Product Security marked this as Low severity because although it could potentially lead to an impact to application availability, no specific impact was demonstrated in this case. This flaw affects ImageMagick versions prior to 7.0.9-0.","severity_level":"NoInfo","cwe":"CWE-190","cve":"CVE-2020-27771"}} -{"idx":204657,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char *name, s[2]; const char *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if ((image->storage_class != PseudoClass) && (image->colormap != (PixelInfo *) NULL)) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; if (image->depth != GetImageDepth(image,exception)) (void) SetImageDepth(image,image->depth,exception); for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *r; register Quantum *q; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { r=GetVirtualPixels(image,0,y,image->columns,1,exception); if (r == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,r) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image,r,opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,r,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image,r,opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,r) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image,r,transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,r); ping_trans_color.green=(unsigned short) GetPixelGreen(image,r); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,r); ping_trans_color.gray=(unsigned short) GetPixelGray(image,r); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,r,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,r,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,r,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,r,semitransparent+i) && GetPixelAlpha(image,r) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image,r,semitransparent+i); } } } r+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } if (number_opaque < 259) { for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != GetPixelGreen(image,r) || GetPixelRed(image,r) != GetPixelBlue(image,r)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != 0 && GetPixelRed(image,r) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,q); SetPixelAlpha(image,TransparentAlpha,q); } else SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR04PixelRGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR03RGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR02PixelBlue(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,q)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,q)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,q)) == 0x00 && GetPixelAlpha(image,q) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } (void) old_bit_depth; image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); \/* write orNT if image->orientation is defined *\/ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); \/* data length=1 *\/ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); \/* PNG uses Exif orientation values *\/ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(ping_pixels,0,rowbytes*sizeof(*ping_pixels)); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) || ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse)) { \/* Palette, Bilevel, or Opaque Monochrome *\/ QuantumType quantum_type; register const Quantum *p; quantum_type=RedQuantum; if (mng_info->IsPalette) { quantum_type=GrayQuantum; if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) quantum_type=IndexQuantum; } SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,ping_pixels,exception); if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"True","vulnerability_types":["Out-of-bounds Read"],"explanation":"WriteOnePNGImage() from coders\/png.c (the PNG coder) has a for loop with an improper exit condition that can allow an out-of-bounds READ via heap-buffer-overflow. This occurs because it is possible for the colormap to have less than 256 valid values but the loop condition will loop 256 times, attempting to pass invalid colormap data to the event logger. The patch replaces the hardcoded 256 value with a call to MagickMin() to ensure the proper value is used. This could impact application availability when a specially crafted input file is processed by ImageMagick. This flaw affects ImageMagick versions prior to 7.0.8-68.","severity_level":"NoInfo","cwe":"CWE-125","cve":"CVE-2020-25674"}} -{"idx":468324,"input":"WandExport MagickBooleanType MogrifyImage(ImageInfo *image_info,const int argc, const char **argv,Image **image,ExceptionInfo *exception) { CompositeOperator compose; const char *format, *option; double attenuate; DrawInfo *draw_info; GeometryInfo geometry_info; ImageInfo *mogrify_info; MagickStatusType status; PixelInfo fill; MagickStatusType flags; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; RectangleInfo geometry, region_geometry; register ssize_t i; \/* Initialize method variables. *\/ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image **) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",(*image)->filename); if (argc < 0) return(MagickTrue); mogrify_info=CloneImageInfo(image_info); draw_info=CloneDrawInfo(mogrify_info,(DrawInfo *) NULL); quantize_info=AcquireQuantizeInfo(mogrify_info); SetGeometryInfo(&geometry_info); GetPixelInfo(*image,&fill); fill=(*image)->background_color; attenuate=1.0; compose=(*image)->compose; interpolate_method=UndefinedInterpolatePixel; format=GetImageOption(mogrify_info,\"format\"); SetGeometry(*image,®ion_geometry); \/* Transmogrify the image. *\/ for (i=0; i < (ssize_t) argc; i++) { Image *mogrify_image; ssize_t count; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=MagickMax(ParseCommandOption(MagickCommandOptions,MagickFalse,option), 0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); mogrify_image=(Image *) NULL; switch (*(option+1)) { case 'a': { if (LocaleCompare(\"adaptive-blur\",option+1) == 0) { \/* Adaptive blur image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=AdaptiveBlurImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"adaptive-resize\",option+1) == 0) { \/* Adaptive resize image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=AdaptiveResizeImage(*image,geometry.width, geometry.height,exception); break; } if (LocaleCompare(\"adaptive-sharpen\",option+1) == 0) { \/* Adaptive sharpen image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=AdaptiveSharpenImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"affine\",option+1) == 0) { \/* Affine matrix. *\/ if (*option == '+') { GetAffineMatrix(&draw_info->affine); break; } (void) ParseAffineGeometry(argv[i+1],&draw_info->affine,exception); break; } if (LocaleCompare(\"alpha\",option+1) == 0) { AlphaChannelOption alpha_type; (void) SyncImageSettings(mogrify_info,*image,exception); alpha_type=(AlphaChannelOption) ParseCommandOption( MagickAlphaChannelOptions,MagickFalse,argv[i+1]); (void) SetImageAlphaChannel(*image,alpha_type,exception); break; } if (LocaleCompare(\"annotate\",option+1) == 0) { char *text, geometry_str[MagickPathExtent]; \/* Annotate image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); SetGeometryInfo(&geometry_info); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; text=InterpretImageProperties(mogrify_info,*image,argv[i+2], exception); if (text == (char *) NULL) break; (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry_str,MagickPathExtent,\"%+f%+f\", geometry_info.xi,geometry_info.psi); (void) CloneString(&draw_info->geometry,geometry_str); draw_info->affine.sx=cos(DegreesToRadians( fmod(geometry_info.rho,360.0))); draw_info->affine.rx=sin(DegreesToRadians( fmod(geometry_info.rho,360.0))); draw_info->affine.ry=(-sin(DegreesToRadians( fmod(geometry_info.sigma,360.0)))); draw_info->affine.sy=cos(DegreesToRadians( fmod(geometry_info.sigma,360.0))); (void) AnnotateImage(*image,draw_info,exception); break; } if (LocaleCompare(\"antialias\",option+1) == 0) { draw_info->stroke_antialias=(*option == '-') ? MagickTrue : MagickFalse; draw_info->text_antialias=(*option == '-') ? MagickTrue : MagickFalse; break; } if (LocaleCompare(\"attenuate\",option+1) == 0) { if (*option == '+') { attenuate=1.0; break; } attenuate=StringToDouble(argv[i+1],(char **) NULL); break; } if (LocaleCompare(\"auto-gamma\",option+1) == 0) { \/* Auto Adjust Gamma of image based on its mean *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) AutoGammaImage(*image,exception); break; } if (LocaleCompare(\"auto-level\",option+1) == 0) { \/* Perfectly Normalize (max\/min stretch) the image *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) AutoLevelImage(*image,exception); break; } if (LocaleCompare(\"auto-orient\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=AutoOrientImage(*image,(*image)->orientation, exception); break; } if (LocaleCompare(\"auto-threshold\",option+1) == 0) { AutoThresholdMethod method; (void) SyncImageSettings(mogrify_info,*image,exception); method=(AutoThresholdMethod) ParseCommandOption( MagickAutoThresholdOptions,MagickFalse,argv[i+1]); (void) AutoThresholdImage(*image,method,exception); break; } break; } case 'b': { if (LocaleCompare(\"black-threshold\",option+1) == 0) { \/* Black threshold image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) BlackThresholdImage(*image,argv[i+1],exception); break; } if (LocaleCompare(\"blue-shift\",option+1) == 0) { \/* Blue shift image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); geometry_info.rho=1.5; if (*option == '-') flags=ParseGeometry(argv[i+1],&geometry_info); mogrify_image=BlueShiftImage(*image,geometry_info.rho,exception); break; } if (LocaleCompare(\"blur\",option+1) == 0) { \/* Gaussian blur image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=0.0; mogrify_image=BlurImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"border\",option+1) == 0) { \/* Surround image with a border of solid color. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=BorderImage(*image,&geometry,compose,exception); break; } if (LocaleCompare(\"bordercolor\",option+1) == 0) { if (*option == '+') { (void) QueryColorCompliance(MogrifyBorderColor,AllCompliance, &draw_info->border_color,exception); break; } (void) QueryColorCompliance(argv[i+1],AllCompliance, &draw_info->border_color,exception); break; } if (LocaleCompare(\"box\",option+1) == 0) { (void) QueryColorCompliance(argv[i+1],AllCompliance, &draw_info->undercolor,exception); break; } if (LocaleCompare(\"brightness-contrast\",option+1) == 0) { double brightness, contrast; \/* Brightness \/ contrast image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); brightness=geometry_info.rho; contrast=0.0; if ((flags & SigmaValue) != 0) contrast=geometry_info.sigma; (void) BrightnessContrastImage(*image,brightness,contrast, exception); break; } break; } case 'c': { if (LocaleCompare(\"canny\",option+1) == 0) { \/* Detect edges in the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=0.10; if ((flags & PsiValue) == 0) geometry_info.psi=0.30; if ((flags & PercentValue) != 0) { geometry_info.xi\/=100.0; geometry_info.psi\/=100.0; } mogrify_image=CannyEdgeImage(*image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,geometry_info.psi,exception); break; } if (LocaleCompare(\"cdl\",option+1) == 0) { char *color_correction_collection; \/* Color correct with a color decision list. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); color_correction_collection=FileToString(argv[i+1],~0UL,exception); if (color_correction_collection == (char *) NULL) break; (void) ColorDecisionListImage(*image,color_correction_collection, exception); break; } if (LocaleCompare(\"channel\",option+1) == 0) { ChannelType channel; (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { (void) SetPixelChannelMask(*image,DefaultChannels); break; } channel=(ChannelType) ParseChannelOption(argv[i+1]); (void) SetPixelChannelMask(*image,channel); break; } if (LocaleCompare(\"charcoal\",option+1) == 0) { \/* Charcoal image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=1.0; mogrify_image=CharcoalImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"chop\",option+1) == 0) { \/* Chop the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseGravityGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ChopImage(*image,&geometry,exception); break; } if (LocaleCompare(\"clip\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { (void) SetImageMask(*image,WritePixelMask,(Image *) NULL, exception); break; } (void) ClipImage(*image,exception); break; } if (LocaleCompare(\"clip-mask\",option+1) == 0) { CacheView *mask_view; Image *mask_image; register Quantum *magick_restrict q; register ssize_t x; ssize_t y; (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { \/* Remove a mask. *\/ (void) SetImageMask(*image,ReadPixelMask,(Image *) NULL, exception); break; } \/* Set the image mask. FUTURE: This Should Be a SetImageAlphaChannel() call, Or two. *\/ mask_image=GetImageCache(mogrify_info,argv[i+1],exception); if (mask_image == (Image *) NULL) break; if (SetImageStorageClass(mask_image,DirectClass,exception) == MagickFalse) return(MagickFalse); mask_view=AcquireAuthenticCacheView(mask_image,exception); for (y=0; y < (ssize_t) mask_image->rows; y++) { q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) mask_image->columns; x++) { if (mask_image->alpha_trait == UndefinedPixelTrait) SetPixelAlpha(mask_image,(Quantum) GetPixelIntensity(mask_image,q),q); SetPixelRed(mask_image,GetPixelAlpha(mask_image,q),q); SetPixelGreen(mask_image,GetPixelAlpha(mask_image,q),q); SetPixelBlue(mask_image,GetPixelAlpha(mask_image,q),q); q+=GetPixelChannels(mask_image); } if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse) break; } mask_view=DestroyCacheView(mask_view); mask_image->alpha_trait=BlendPixelTrait; (void) SetImageMask(*image,ReadPixelMask,mask_image,exception); break; } if (LocaleCompare(\"clip-path\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); (void) ClipImagePath(*image,argv[i+1],*option == '-' ? MagickTrue : MagickFalse,exception); break; } if (LocaleCompare(\"colorize\",option+1) == 0) { \/* Colorize the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=ColorizeImage(*image,argv[i+1],&fill,exception); break; } if (LocaleCompare(\"color-matrix\",option+1) == 0) { KernelInfo *kernel; (void) SyncImageSettings(mogrify_info,*image,exception); kernel=AcquireKernelInfo(argv[i+1],exception); if (kernel == (KernelInfo *) NULL) break; \/* FUTURE: check on size of the matrix *\/ mogrify_image=ColorMatrixImage(*image,kernel,exception); kernel=DestroyKernelInfo(kernel); break; } if (LocaleCompare(\"colors\",option+1) == 0) { \/* Reduce the number of colors in the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); quantize_info->number_colors=StringToUnsignedLong(argv[i+1]); if (quantize_info->number_colors == 0) break; if (((*image)->storage_class == DirectClass) || (*image)->colors > quantize_info->number_colors) (void) QuantizeImage(quantize_info,*image,exception); else (void) CompressImageColormap(*image,exception); break; } if (LocaleCompare(\"colorspace\",option+1) == 0) { ColorspaceType colorspace; (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { (void) TransformImageColorspace(*image,sRGBColorspace, exception); break; } colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); (void) TransformImageColorspace(*image,colorspace,exception); break; } if (LocaleCompare(\"compose\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"connected-components\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=ConnectedComponentsImage(*image,(size_t) StringToInteger(argv[i+1]),(CCObjectInfo **) NULL,exception); break; } if (LocaleCompare(\"contrast\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); (void) ContrastImage(*image,(*option == '-') ? MagickTrue : MagickFalse,exception); break; } if (LocaleCompare(\"contrast-stretch\",option+1) == 0) { double black_point, white_point; \/* Contrast stretch image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); black_point=geometry_info.rho; white_point=(flags & SigmaValue) != 0 ? geometry_info.sigma : black_point; if ((flags & PercentValue) != 0) { black_point*=(double) (*image)->columns*(*image)->rows\/100.0; white_point*=(double) (*image)->columns*(*image)->rows\/100.0; } white_point=(double) (*image)->columns*(*image)->rows- white_point; (void) ContrastStretchImage(*image,black_point,white_point, exception); break; } if (LocaleCompare(\"convolve\",option+1) == 0) { double gamma; KernelInfo *kernel_info; register ssize_t j; size_t extent; (void) SyncImageSettings(mogrify_info,*image,exception); kernel_info=AcquireKernelInfo(argv[i+1],exception); if (kernel_info == (KernelInfo *) NULL) break; extent=kernel_info->width*kernel_info->height; gamma=0.0; for (j=0; j < (ssize_t) extent; j++) gamma+=kernel_info->values[j]; gamma=1.0\/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma); for (j=0; j < (ssize_t) extent; j++) kernel_info->values[j]*=gamma; mogrify_image=MorphologyImage(*image,CorrelateMorphology,1, kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"crop\",option+1) == 0) { \/* Crop a image to a smaller size *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=CropImageToTiles(*image,argv[i+1],exception); break; } if (LocaleCompare(\"cycle\",option+1) == 0) { \/* Cycle an image colormap. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) CycleColormapImage(*image,(ssize_t) StringToLong(argv[i+1]), exception); break; } break; } case 'd': { if (LocaleCompare(\"decipher\",option+1) == 0) { StringInfo *passkey; \/* Decipher pixels. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); passkey=FileToStringInfo(argv[i+1],~0UL,exception); if (passkey != (StringInfo *) NULL) { (void) PasskeyDecipherImage(*image,passkey,exception); passkey=DestroyStringInfo(passkey); } break; } if (LocaleCompare(\"density\",option+1) == 0) { \/* Set image density. *\/ (void) CloneString(&draw_info->density,argv[i+1]); break; } if (LocaleCompare(\"depth\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { (void) SetImageDepth(*image,MAGICKCORE_QUANTUM_DEPTH,exception); break; } (void) SetImageDepth(*image,StringToUnsignedLong(argv[i+1]), exception); break; } if (LocaleCompare(\"deskew\",option+1) == 0) { double threshold; \/* Straighten the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') threshold=40.0*QuantumRange\/100.0; else threshold=StringToDoubleInterval(argv[i+1],(double) QuantumRange+ 1.0); mogrify_image=DeskewImage(*image,threshold,exception); break; } if (LocaleCompare(\"despeckle\",option+1) == 0) { \/* Reduce the speckles within an image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=DespeckleImage(*image,exception); break; } if (LocaleCompare(\"display\",option+1) == 0) { (void) CloneString(&draw_info->server_name,argv[i+1]); break; } if (LocaleCompare(\"distort\",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; DistortMethod method; double *arguments; register ssize_t x; size_t number_arguments; \/* Distort image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); method=(DistortMethod) ParseCommandOption(MagickDistortOptions, MagickFalse,argv[i+1]); if (method == ResizeDistortion) { double resize_args[2]; \/* Special Case - Argument is actually a resize geometry! Convert that to an appropriate distortion argument array. *\/ (void) ParseRegionGeometry(*image,argv[i+2],&geometry, exception); resize_args[0]=(double) geometry.width; resize_args[1]=(double) geometry.height; mogrify_image=DistortImage(*image,method,(size_t)2, resize_args,MagickTrue,exception); break; } args=InterpretImageProperties(mogrify_info,*image,argv[i+2], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, \"MemoryAllocationFailed\",(*image)->filename); (void) ResetMagickMemory(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); mogrify_image=DistortImage(*image,method,number_arguments,arguments, (*option == '+') ? MagickTrue : MagickFalse,exception); arguments=(double *) RelinquishMagickMemory(arguments); break; } if (LocaleCompare(\"dither\",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"draw\",option+1) == 0) { \/* Draw image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) CloneString(&draw_info->primitive,argv[i+1]); (void) DrawImage(*image,draw_info,exception); break; } break; } case 'e': { if (LocaleCompare(\"edge\",option+1) == 0) { \/* Enhance edges in the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); mogrify_image=EdgeImage(*image,geometry_info.rho,exception); break; } if (LocaleCompare(\"emboss\",option+1) == 0) { \/* Emboss image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=EmbossImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"encipher\",option+1) == 0) { StringInfo *passkey; \/* Encipher pixels. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); passkey=FileToStringInfo(argv[i+1],~0UL,exception); if (passkey != (StringInfo *) NULL) { (void) PasskeyEncipherImage(*image,passkey,exception); passkey=DestroyStringInfo(passkey); } break; } if (LocaleCompare(\"encoding\",option+1) == 0) { (void) CloneString(&draw_info->encoding,argv[i+1]); break; } if (LocaleCompare(\"enhance\",option+1) == 0) { \/* Enhance image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=EnhanceImage(*image,exception); break; } if (LocaleCompare(\"equalize\",option+1) == 0) { \/* Equalize image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) EqualizeImage(*image,exception); break; } if (LocaleCompare(\"evaluate\",option+1) == 0) { double constant; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*image,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); constant=StringToDoubleInterval(argv[i+2],(double) QuantumRange+ 1.0); (void) EvaluateImage(*image,op,constant,exception); break; } if (LocaleCompare(\"extent\",option+1) == 0) { \/* Set the image extent. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGravityGeometry(*image,argv[i+1],&geometry,exception); if (geometry.width == 0) geometry.width=(*image)->columns; if (geometry.height == 0) geometry.height=(*image)->rows; mogrify_image=ExtentImage(*image,&geometry,exception); break; } break; } case 'f': { if (LocaleCompare(\"family\",option+1) == 0) { if (*option == '+') { if (draw_info->family != (char *) NULL) draw_info->family=DestroyString(draw_info->family); break; } (void) CloneString(&draw_info->family,argv[i+1]); break; } if (LocaleCompare(\"features\",option+1) == 0) { if (*option == '+') { (void) DeleteImageArtifact(*image,\"identify:features\"); break; } (void) SetImageArtifact(*image,\"identify:features\",argv[i+1]); (void) SetImageArtifact(*image,\"verbose\",\"true\"); break; } if (LocaleCompare(\"fill\",option+1) == 0) { ExceptionInfo *sans; PixelInfo color; GetPixelInfo(*image,&fill); if (*option == '+') { (void) QueryColorCompliance(\"none\",AllCompliance,&fill, exception); draw_info->fill=fill; if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); break; } sans=AcquireExceptionInfo(); status=QueryColorCompliance(argv[i+1],AllCompliance,&color,sans); sans=DestroyExceptionInfo(sans); if (status == MagickFalse) draw_info->fill_pattern=GetImageCache(mogrify_info,argv[i+1], exception); else draw_info->fill=fill=color; break; } if (LocaleCompare(\"flip\",option+1) == 0) { \/* Flip image scanlines. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=FlipImage(*image,exception); break; } if (LocaleCompare(\"floodfill\",option+1) == 0) { PixelInfo target; \/* Floodfill image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParsePageGeometry(*image,argv[i+1],&geometry,exception); (void) QueryColorCompliance(argv[i+2],AllCompliance,&target, exception); (void) FloodfillPaintImage(*image,draw_info,&target,geometry.x, geometry.y,*option == '-' ? MagickFalse : MagickTrue,exception); break; } if (LocaleCompare(\"flop\",option+1) == 0) { \/* Flop image scanlines. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=FlopImage(*image,exception); break; } if (LocaleCompare(\"font\",option+1) == 0) { if (*option == '+') { if (draw_info->font != (char *) NULL) draw_info->font=DestroyString(draw_info->font); break; } (void) CloneString(&draw_info->font,argv[i+1]); break; } if (LocaleCompare(\"format\",option+1) == 0) { format=argv[i+1]; break; } if (LocaleCompare(\"frame\",option+1) == 0) { FrameInfo frame_info; \/* Surround image with an ornamental border. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); frame_info.width=geometry.width; frame_info.height=geometry.height; frame_info.outer_bevel=geometry.x; frame_info.inner_bevel=geometry.y; frame_info.x=(ssize_t) frame_info.width; frame_info.y=(ssize_t) frame_info.height; frame_info.width=(*image)->columns+2*frame_info.width; frame_info.height=(*image)->rows+2*frame_info.height; mogrify_image=FrameImage(*image,&frame_info,compose,exception); break; } if (LocaleCompare(\"function\",option+1) == 0) { char *arguments, token[MagickPathExtent]; const char *p; double *parameters; MagickFunction function; register ssize_t x; size_t number_parameters; \/* Function Modify Image Values *\/ (void) SyncImageSettings(mogrify_info,*image,exception); function=(MagickFunction) ParseCommandOption(MagickFunctionOptions, MagickFalse,argv[i+1]); arguments=InterpretImageProperties(mogrify_info,*image,argv[i+2], exception); if (arguments == (char *) NULL) break; p=(char *) arguments; for (x=0; *p != '\\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_parameters=(size_t) x; parameters=(double *) AcquireQuantumMemory(number_parameters, sizeof(*parameters)); if (parameters == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, \"MemoryAllocationFailed\",(*image)->filename); (void) ResetMagickMemory(parameters,0,number_parameters* sizeof(*parameters)); p=(char *) arguments; for (x=0; (x < (ssize_t) number_parameters) && (*p != '\\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); parameters[x]=StringToDouble(token,(char **) NULL); } arguments=DestroyString(arguments); (void) FunctionImage(*image,function,number_parameters,parameters, exception); parameters=(double *) RelinquishMagickMemory(parameters); break; } break; } case 'g': { if (LocaleCompare(\"gamma\",option+1) == 0) { \/* Gamma image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') (*image)->gamma=StringToDouble(argv[i+1],(char **) NULL); else (void) GammaImage(*image,StringToDouble(argv[i+1],(char **) NULL), exception); break; } if ((LocaleCompare(\"gaussian-blur\",option+1) == 0) || (LocaleCompare(\"gaussian\",option+1) == 0)) { \/* Gaussian blur image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=GaussianBlurImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"geometry\",option+1) == 0) { \/* Record Image offset, Resize last image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { if ((*image)->geometry != (char *) NULL) (*image)->geometry=DestroyString((*image)->geometry); break; } flags=ParseRegionGeometry(*image,argv[i+1],&geometry,exception); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) (void) CloneString(&(*image)->geometry,argv[i+1]); else mogrify_image=ResizeImage(*image,geometry.width,geometry.height, (*image)->filter,exception); break; } if (LocaleCompare(\"gravity\",option+1) == 0) { if (*option == '+') { draw_info->gravity=UndefinedGravity; break; } draw_info->gravity=(GravityType) ParseCommandOption( MagickGravityOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"grayscale\",option+1) == 0) { PixelIntensityMethod method; (void) SyncImageSettings(mogrify_info,*image,exception); method=(PixelIntensityMethod) ParseCommandOption( MagickPixelIntensityOptions,MagickFalse,argv[i+1]); (void) GrayscaleImage(*image,method,exception); break; } break; } case 'h': { if (LocaleCompare(\"highlight-color\",option+1) == 0) { (void) SetImageArtifact(*image,\"compare:highlight-color\",argv[i+1]); break; } if (LocaleCompare(\"hough-lines\",option+1) == 0) { \/* Detect edges in the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if ((flags & XiValue) == 0) geometry_info.xi=40; mogrify_image=HoughLineImage(*image,(size_t) geometry_info.rho, (size_t) geometry_info.sigma,(size_t) geometry_info.xi,exception); break; } break; } case 'i': { if (LocaleCompare(\"identify\",option+1) == 0) { char *text; (void) SyncImageSettings(mogrify_info,*image,exception); if (format == (char *) NULL) { (void) IdentifyImage(*image,stdout,mogrify_info->verbose, exception); break; } text=InterpretImageProperties(mogrify_info,*image,format, exception); if (text == (char *) NULL) break; (void) fputs(text,stdout); text=DestroyString(text); break; } if (LocaleCompare(\"implode\",option+1) == 0) { \/* Implode image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=ImplodeImage(*image,geometry_info.rho, interpolate_method,exception); break; } if (LocaleCompare(\"interline-spacing\",option+1) == 0) { if (*option == '+') (void) ParseGeometry(\"0\",&geometry_info); else (void) ParseGeometry(argv[i+1],&geometry_info); draw_info->interline_spacing=geometry_info.rho; break; } if (LocaleCompare(\"interpolate\",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"interword-spacing\",option+1) == 0) { if (*option == '+') (void) ParseGeometry(\"0\",&geometry_info); else (void) ParseGeometry(argv[i+1],&geometry_info); draw_info->interword_spacing=geometry_info.rho; break; } if (LocaleCompare(\"interpolative-resize\",option+1) == 0) { \/* Interpolative resize image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=InterpolativeResizeImage(*image,geometry.width, geometry.height,interpolate_method,exception); break; } break; } case 'k': { if (LocaleCompare(\"kerning\",option+1) == 0) { if (*option == '+') (void) ParseGeometry(\"0\",&geometry_info); else (void) ParseGeometry(argv[i+1],&geometry_info); draw_info->kerning=geometry_info.rho; break; } if (LocaleCompare(\"kuwahara\",option+1) == 0) { \/* Edge preserving blur. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho-0.5; mogrify_image=KuwaharaImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } break; } case 'l': { if (LocaleCompare(\"lat\",option+1) == 0) { \/* Local adaptive threshold image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & PercentValue) != 0) geometry_info.xi=(double) QuantumRange*geometry_info.xi\/100.0; mogrify_image=AdaptiveThresholdImage(*image,(size_t) geometry_info.rho,(size_t) geometry_info.sigma,(double) geometry_info.xi,exception); break; } if (LocaleCompare(\"level\",option+1) == 0) { double black_point, gamma, white_point; \/* Parse levels. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); black_point=geometry_info.rho; white_point=(double) QuantumRange; if ((flags & SigmaValue) != 0) white_point=geometry_info.sigma; gamma=1.0; if ((flags & XiValue) != 0) gamma=geometry_info.xi; if ((flags & PercentValue) != 0) { black_point*=(double) (QuantumRange\/100.0); white_point*=(double) (QuantumRange\/100.0); } if ((flags & SigmaValue) == 0) white_point=(double) QuantumRange-black_point; if ((*option == '+') || ((flags & AspectValue) != 0)) (void) LevelizeImage(*image,black_point,white_point,gamma, exception); else (void) LevelImage(*image,black_point,white_point,gamma, exception); break; } if (LocaleCompare(\"level-colors\",option+1) == 0) { char token[MagickPathExtent]; const char *p; PixelInfo black_point, white_point; p=(const char *) argv[i+1]; GetNextToken(p,&p,MagickPathExtent,token); \/* get black point color *\/ if ((isalpha((int) *token) != 0) || ((*token == '#') != 0)) (void) QueryColorCompliance(token,AllCompliance, &black_point,exception); else (void) QueryColorCompliance(\"#000000\",AllCompliance, &black_point,exception); if (isalpha((int) token[0]) || (token[0] == '#')) GetNextToken(p,&p,MagickPathExtent,token); if (*token == '\\0') white_point=black_point; \/* set everything to that color *\/ else { if ((isalpha((int) *token) == 0) && ((*token == '#') == 0)) GetNextToken(p,&p,MagickPathExtent,token); \/* Get white point color. *\/ if ((isalpha((int) *token) != 0) || ((*token == '#') != 0)) (void) QueryColorCompliance(token,AllCompliance, &white_point,exception); else (void) QueryColorCompliance(\"#ffffff\",AllCompliance, &white_point,exception); } (void) LevelImageColors(*image,&black_point,&white_point, *option == '+' ? MagickTrue : MagickFalse,exception); break; } if (LocaleCompare(\"linear-stretch\",option+1) == 0) { double black_point, white_point; (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); black_point=geometry_info.rho; white_point=(double) (*image)->columns*(*image)->rows; if ((flags & SigmaValue) != 0) white_point=geometry_info.sigma; if ((flags & PercentValue) != 0) { black_point*=(double) (*image)->columns*(*image)->rows\/100.0; white_point*=(double) (*image)->columns*(*image)->rows\/100.0; } if ((flags & SigmaValue) == 0) white_point=(double) (*image)->columns*(*image)->rows- black_point; (void) LinearStretchImage(*image,black_point,white_point,exception); break; } if (LocaleCompare(\"liquid-rescale\",option+1) == 0) { \/* Liquid rescale image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseRegionGeometry(*image,argv[i+1],&geometry,exception); if ((flags & XValue) == 0) geometry.x=1; if ((flags & YValue) == 0) geometry.y=0; mogrify_image=LiquidRescaleImage(*image,geometry.width, geometry.height,1.0*geometry.x,1.0*geometry.y,exception); break; } if (LocaleCompare(\"local-contrast\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & RhoValue) == 0) geometry_info.rho=10; if ((flags & SigmaValue) == 0) geometry_info.sigma=12.5; mogrify_image=LocalContrastImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"lowlight-color\",option+1) == 0) { (void) SetImageArtifact(*image,\"compare:lowlight-color\",argv[i+1]); break; } break; } case 'm': { if (LocaleCompare(\"magnify\",option+1) == 0) { \/* Double image size. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=MagnifyImage(*image,exception); break; } if (LocaleCompare(\"map\",option+1) == 0) { Image *remap_image; \/* Transform image colors to match this set of colors. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') break; remap_image=GetImageCache(mogrify_info,argv[i+1],exception); if (remap_image == (Image *) NULL) break; (void) RemapImage(quantize_info,*image,remap_image,exception); remap_image=DestroyImage(remap_image); break; } if (LocaleCompare(\"mask\",option+1) == 0) { Image *mask; (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { \/* Remove a mask. *\/ (void) SetImageMask(*image,WritePixelMask,(Image *) NULL, exception); break; } \/* Set the image mask. *\/ mask=GetImageCache(mogrify_info,argv[i+1],exception); if (mask == (Image *) NULL) break; (void) NegateImage(mask,MagickFalse,exception); (void) SetImageMask(*image,WritePixelMask,mask,exception); mask=DestroyImage(mask); break; } if (LocaleCompare(\"matte\",option+1) == 0) { (void) SetImageAlphaChannel(*image,(*option == '-') ? SetAlphaChannel : DeactivateAlphaChannel,exception); break; } if (LocaleCompare(\"mean-shift\",option+1) == 0) { \/* Detect edges in the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if ((flags & XiValue) == 0) geometry_info.xi=0.10*QuantumRange; if ((flags & PercentValue) != 0) geometry_info.xi=(double) QuantumRange*geometry_info.xi\/100.0; mogrify_image=MeanShiftImage(*image,(size_t) geometry_info.rho, (size_t) geometry_info.sigma,geometry_info.xi,exception); break; } if (LocaleCompare(\"median\",option+1) == 0) { \/* Median filter image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; mogrify_image=StatisticImage(*image,MedianStatistic,(size_t) geometry_info.rho,(size_t) geometry_info.sigma,exception); break; } if (LocaleCompare(\"mode\",option+1) == 0) { \/* Mode image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; mogrify_image=StatisticImage(*image,ModeStatistic,(size_t) geometry_info.rho,(size_t) geometry_info.sigma,exception); break; } if (LocaleCompare(\"modulate\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); (void) ModulateImage(*image,argv[i+1],exception); break; } if (LocaleCompare(\"moments\",option+1) == 0) { if (*option == '+') { (void) DeleteImageArtifact(*image,\"identify:moments\"); break; } (void) SetImageArtifact(*image,\"identify:moments\",argv[i+1]); (void) SetImageArtifact(*image,\"verbose\",\"true\"); break; } if (LocaleCompare(\"monitor\",option+1) == 0) { if (*option == '+') { (void) SetImageProgressMonitor(*image, (MagickProgressMonitor) NULL,(void *) NULL); break; } (void) SetImageProgressMonitor(*image,MonitorProgress, (void *) NULL); break; } if (LocaleCompare(\"monochrome\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); (void) SetImageType(*image,BilevelType,exception); break; } if (LocaleCompare(\"morphology\",option+1) == 0) { char token[MagickPathExtent]; const char *p; KernelInfo *kernel; MorphologyMethod method; ssize_t iterations; \/* Morphological Image Operation *\/ (void) SyncImageSettings(mogrify_info,*image,exception); p=argv[i+1]; GetNextToken(p,&p,MagickPathExtent,token); method=(MorphologyMethod) ParseCommandOption( MagickMorphologyOptions,MagickFalse,token); iterations=1L; GetNextToken(p,&p,MagickPathExtent,token); if ((*p == ':') || (*p == ',')) GetNextToken(p,&p,MagickPathExtent,token); if ((*p != '\\0')) iterations=(ssize_t) StringToLong(p); kernel=AcquireKernelInfo(argv[i+2],exception); if (kernel == (KernelInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"UnabletoParseKernel\",\"morphology\"); status=MagickFalse; break; } mogrify_image=MorphologyImage(*image,method,iterations,kernel, exception); kernel=DestroyKernelInfo(kernel); break; } if (LocaleCompare(\"motion-blur\",option+1) == 0) { \/* Motion blur image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=MotionBlurImage(*image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,exception); break; } break; } case 'n': { if (LocaleCompare(\"negate\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); (void) NegateImage(*image,*option == '+' ? MagickTrue : MagickFalse,exception); break; } if (LocaleCompare(\"noise\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '-') { flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; mogrify_image=StatisticImage(*image,NonpeakStatistic,(size_t) geometry_info.rho,(size_t) geometry_info.sigma,exception); } else { NoiseType noise; noise=(NoiseType) ParseCommandOption(MagickNoiseOptions, MagickFalse,argv[i+1]); mogrify_image=AddNoiseImage(*image,noise,attenuate,exception); } break; } if (LocaleCompare(\"normalize\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); (void) NormalizeImage(*image,exception); break; } break; } case 'o': { if (LocaleCompare(\"opaque\",option+1) == 0) { PixelInfo target; (void) SyncImageSettings(mogrify_info,*image,exception); (void) QueryColorCompliance(argv[i+1],AllCompliance,&target, exception); (void) OpaquePaintImage(*image,&target,&fill,*option == '-' ? MagickFalse : MagickTrue,exception); break; } if (LocaleCompare(\"ordered-dither\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); (void) OrderedDitherImage(*image,argv[i+1],exception); break; } break; } case 'p': { if (LocaleCompare(\"paint\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=OilPaintImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"perceptible\",option+1) == 0) { \/* Perceptible image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) PerceptibleImage(*image,StringToDouble(argv[i+1], (char **) NULL),exception); break; } if (LocaleCompare(\"pointsize\",option+1) == 0) { if (*option == '+') (void) ParseGeometry(\"12\",&geometry_info); else (void) ParseGeometry(argv[i+1],&geometry_info); draw_info->pointsize=geometry_info.rho; break; } if (LocaleCompare(\"polaroid\",option+1) == 0) { const char *caption; double angle; RandomInfo *random_info; \/* Simulate a Polaroid picture. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); random_info=AcquireRandomInfo(); angle=22.5*(GetPseudoRandomValue(random_info)-0.5); random_info=DestroyRandomInfo(random_info); if (*option == '-') { SetGeometryInfo(&geometry_info); flags=ParseGeometry(argv[i+1],&geometry_info); angle=geometry_info.rho; } caption=GetImageProperty(*image,\"caption\",exception); mogrify_image=PolaroidImage(*image,draw_info,caption,angle, interpolate_method,exception); break; } if (LocaleCompare(\"posterize\",option+1) == 0) { \/* Posterize image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) PosterizeImage(*image,StringToUnsignedLong(argv[i+1]), quantize_info->dither_method,exception); break; } if (LocaleCompare(\"preview\",option+1) == 0) { PreviewType preview_type; \/* Preview image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') preview_type=UndefinedPreview; else preview_type=(PreviewType) ParseCommandOption( MagickPreviewOptions,MagickFalse,argv[i+1]); mogrify_image=PreviewImage(*image,preview_type,exception); break; } if (LocaleCompare(\"profile\",option+1) == 0) { const char *name; const StringInfo *profile; Image *profile_image; ImageInfo *profile_info; (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { \/* Remove a profile from the image. *\/ (void) ProfileImage(*image,argv[i+1],(const unsigned char *) NULL,0,exception); break; } \/* Associate a profile with the image. *\/ profile_info=CloneImageInfo(mogrify_info); profile=GetImageProfile(*image,\"iptc\"); if (profile != (StringInfo *) NULL) profile_info->profile=(void *) CloneStringInfo(profile); profile_image=GetImageCache(profile_info,argv[i+1],exception); profile_info=DestroyImageInfo(profile_info); if (profile_image == (Image *) NULL) { StringInfo *file_data; profile_info=CloneImageInfo(mogrify_info); (void) CopyMagickString(profile_info->filename,argv[i+1], MagickPathExtent); file_data=FileToStringInfo(profile_info->filename,~0UL, exception); if (file_data != (StringInfo *) NULL) { (void) ProfileImage(*image,profile_info->magick, GetStringInfoDatum(file_data), GetStringInfoLength(file_data),exception); file_data=DestroyStringInfo(file_data); } profile_info=DestroyImageInfo(profile_info); break; } ResetImageProfileIterator(profile_image); name=GetNextImageProfile(profile_image); while (name != (const char *) NULL) { profile=GetImageProfile(profile_image,name); if (profile != (StringInfo *) NULL) (void) ProfileImage(*image,name,GetStringInfoDatum(profile), (size_t) GetStringInfoLength(profile),exception); name=GetNextImageProfile(profile_image); } profile_image=DestroyImage(profile_image); break; } break; } case 'q': { if (LocaleCompare(\"quantize\",option+1) == 0) { if (*option == '+') { quantize_info->colorspace=UndefinedColorspace; break; } quantize_info->colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); break; } break; } case 'r': { if (LocaleCompare(\"rotational-blur\",option+1) == 0) { \/* Rotational blur image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); mogrify_image=RotationalBlurImage(*image,geometry_info.rho,exception); break; } if (LocaleCompare(\"raise\",option+1) == 0) { \/* Surround image with a raise of solid color. *\/ flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); (void) RaiseImage(*image,&geometry,*option == '-' ? MagickTrue : MagickFalse,exception); break; } if (LocaleCompare(\"random-threshold\",option+1) == 0) { \/* Threshold image. *\/ double min_threshold, max_threshold; (void) SyncImageSettings(mogrify_info,*image,exception); min_threshold=0.0; max_threshold=(double) QuantumRange; flags=ParseGeometry(argv[i+1],&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(argv[i+1],'%') != (char *) NULL) { max_threshold*=(double) (0.01*QuantumRange); min_threshold*=(double) (0.01*QuantumRange); } (void) RandomThresholdImage(*image,min_threshold,max_threshold, exception); break; } if (LocaleCompare(\"read-mask\",option+1) == 0) { Image *mask; (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { \/* Remove a mask. *\/ (void) SetImageMask(*image,ReadPixelMask,(Image *) NULL, exception); break; } \/* Set the image mask. *\/ mask=GetImageCache(mogrify_info,argv[i+1],exception); if (mask == (Image *) NULL) break; (void) SetImageMask(*image,ReadPixelMask,mask,exception); mask=DestroyImage(mask); break; } if (LocaleCompare(\"region\",option+1) == 0) { \/* Apply read mask as defined by a region geometry. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { (void) SetImageRegionMask(*image,WritePixelMask, (const RectangleInfo *) NULL,exception); break; } (void) ParseGravityGeometry(*image,argv[i+1],&geometry,exception); (void) SetImageRegionMask(*image,WritePixelMask,&geometry, exception); break; } if (LocaleCompare(\"render\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image,exception); draw_info->render=(*option == '+') ? MagickTrue : MagickFalse; break; } if (LocaleCompare(\"remap\",option+1) == 0) { Image *remap_image; \/* Transform image colors to match this set of colors. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') break; remap_image=GetImageCache(mogrify_info,argv[i+1],exception); if (remap_image == (Image *) NULL) break; (void) RemapImage(quantize_info,*image,remap_image,exception); remap_image=DestroyImage(remap_image); break; } if (LocaleCompare(\"repage\",option+1) == 0) { if (*option == '+') { (void) ParseAbsoluteGeometry(\"0x0+0+0\",&(*image)->page); break; } (void) ResetImagePage(*image,argv[i+1]); break; } if (LocaleCompare(\"resample\",option+1) == 0) { \/* Resample image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; mogrify_image=ResampleImage(*image,geometry_info.rho, geometry_info.sigma,(*image)->filter,exception); break; } if (LocaleCompare(\"resize\",option+1) == 0) { \/* Resize image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ResizeImage(*image,geometry.width,geometry.height, (*image)->filter,exception); break; } if (LocaleCompare(\"roll\",option+1) == 0) { \/* Roll image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); if ((flags & PercentValue) != 0) { geometry.x*=(double) (*image)->columns\/100.0; geometry.y*=(double) (*image)->rows\/100.0; } mogrify_image=RollImage(*image,geometry.x,geometry.y,exception); break; } if (LocaleCompare(\"rotate\",option+1) == 0) { char *rotation; \/* Check for conditional image rotation. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); if (strchr(argv[i+1],'>') != (char *) NULL) if ((*image)->columns <= (*image)->rows) break; if (strchr(argv[i+1],'<') != (char *) NULL) if ((*image)->columns >= (*image)->rows) break; \/* Rotate image. *\/ rotation=ConstantString(argv[i+1]); (void) SubstituteString(&rotation,\">\",\"\"); (void) SubstituteString(&rotation,\"<\",\"\"); (void) ParseGeometry(rotation,&geometry_info); rotation=DestroyString(rotation); mogrify_image=RotateImage(*image,geometry_info.rho,exception); break; } break; } case 's': { if (LocaleCompare(\"sample\",option+1) == 0) { \/* Sample image with pixel replication. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=SampleImage(*image,geometry.width,geometry.height, exception); break; } if (LocaleCompare(\"scale\",option+1) == 0) { \/* Resize image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ScaleImage(*image,geometry.width,geometry.height, exception); break; } if (LocaleCompare(\"selective-blur\",option+1) == 0) { \/* Selectively blur pixels within a contrast threshold. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & PercentValue) != 0) geometry_info.xi=(double) QuantumRange*geometry_info.xi\/100.0; mogrify_image=SelectiveBlurImage(*image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,exception); break; } if (LocaleCompare(\"separate\",option+1) == 0) { \/* Break channels into separate images. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=SeparateImages(*image,exception); break; } if (LocaleCompare(\"sepia-tone\",option+1) == 0) { double threshold; \/* Sepia-tone image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); threshold=StringToDoubleInterval(argv[i+1],(double) QuantumRange+ 1.0); mogrify_image=SepiaToneImage(*image,threshold,exception); break; } if (LocaleCompare(\"segment\",option+1) == 0) { \/* Segment image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; (void) SegmentImage(*image,(*image)->colorspace, mogrify_info->verbose,geometry_info.rho,geometry_info.sigma, exception); break; } if (LocaleCompare(\"set\",option+1) == 0) { char *value; \/* Set image option. *\/ if (*option == '+') { if (LocaleNCompare(argv[i+1],\"registry:\",9) == 0) (void) DeleteImageRegistry(argv[i+1]+9); else if (LocaleNCompare(argv[i+1],\"option:\",7) == 0) { (void) DeleteImageOption(mogrify_info,argv[i+1]+7); (void) DeleteImageArtifact(*image,argv[i+1]+7); } else (void) DeleteImageProperty(*image,argv[i+1]); break; } value=InterpretImageProperties(mogrify_info,*image,argv[i+2], exception); if (value == (char *) NULL) break; if (LocaleNCompare(argv[i+1],\"registry:\",9) == 0) (void) SetImageRegistry(StringRegistryType,argv[i+1]+9,value, exception); else if (LocaleNCompare(argv[i+1],\"option:\",7) == 0) { (void) SetImageOption(image_info,argv[i+1]+7,value); (void) SetImageOption(mogrify_info,argv[i+1]+7,value); (void) SetImageArtifact(*image,argv[i+1]+7,value); } else (void) SetImageProperty(*image,argv[i+1],value,exception); value=DestroyString(value); break; } if (LocaleCompare(\"shade\",option+1) == 0) { \/* Shade image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=ShadeImage(*image,(*option == '-') ? MagickTrue : MagickFalse,geometry_info.rho,geometry_info.sigma,exception); break; } if (LocaleCompare(\"shadow\",option+1) == 0) { \/* Shadow image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=4.0; if ((flags & PsiValue) == 0) geometry_info.psi=4.0; mogrify_image=ShadowImage(*image,geometry_info.rho, geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5), (ssize_t) ceil(geometry_info.psi-0.5),exception); break; } if (LocaleCompare(\"sharpen\",option+1) == 0) { \/* Sharpen image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=0.0; mogrify_image=SharpenImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"shave\",option+1) == 0) { \/* Shave the image edges. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ShaveImage(*image,&geometry,exception); break; } if (LocaleCompare(\"shear\",option+1) == 0) { \/* Shear image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; mogrify_image=ShearImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"sigmoidal-contrast\",option+1) == 0) { \/* Sigmoidal non-linearity contrast control. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=(double) QuantumRange\/2.0; if ((flags & PercentValue) != 0) geometry_info.sigma=(double) QuantumRange*geometry_info.sigma\/ 100.0; (void) SigmoidalContrastImage(*image,(*option == '-') ? MagickTrue : MagickFalse,geometry_info.rho,geometry_info.sigma, exception); break; } if (LocaleCompare(\"sketch\",option+1) == 0) { \/* Sketch image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=SketchImage(*image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,exception); break; } if (LocaleCompare(\"solarize\",option+1) == 0) { double threshold; (void) SyncImageSettings(mogrify_info,*image,exception); threshold=StringToDoubleInterval(argv[i+1],(double) QuantumRange+ 1.0); (void) SolarizeImage(*image,threshold,exception); break; } if (LocaleCompare(\"sparse-color\",option+1) == 0) { SparseColorMethod method; char *arguments; \/* Sparse Color Interpolated Gradient *\/ (void) SyncImageSettings(mogrify_info,*image,exception); method=(SparseColorMethod) ParseCommandOption( MagickSparseColorOptions,MagickFalse,argv[i+1]); arguments=InterpretImageProperties(mogrify_info,*image,argv[i+2], exception); if (arguments == (char *) NULL) break; mogrify_image=SparseColorOption(*image,method,arguments, option[0] == '+' ? MagickTrue : MagickFalse,exception); arguments=DestroyString(arguments); break; } if (LocaleCompare(\"splice\",option+1) == 0) { \/* Splice a solid color into the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseGravityGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=SpliceImage(*image,&geometry,exception); break; } if (LocaleCompare(\"spread\",option+1) == 0) { \/* Spread an image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=SpreadImage(*image,interpolate_method, geometry_info.rho,exception); break; } if (LocaleCompare(\"statistic\",option+1) == 0) { StatisticType type; (void) SyncImageSettings(mogrify_info,*image,exception); type=(StatisticType) ParseCommandOption(MagickStatisticOptions, MagickFalse,argv[i+1]); (void) ParseGeometry(argv[i+2],&geometry_info); mogrify_image=StatisticImage(*image,type,(size_t) geometry_info.rho, (size_t) geometry_info.sigma,exception); break; } if (LocaleCompare(\"stretch\",option+1) == 0) { if (*option == '+') { draw_info->stretch=UndefinedStretch; break; } draw_info->stretch=(StretchType) ParseCommandOption( MagickStretchOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"strip\",option+1) == 0) { \/* Strip image of profiles and comments. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) StripImage(*image,exception); break; } if (LocaleCompare(\"stroke\",option+1) == 0) { ExceptionInfo *sans; PixelInfo color; if (*option == '+') { (void) QueryColorCompliance(\"none\",AllCompliance, &draw_info->stroke,exception); if (draw_info->stroke_pattern != (Image *) NULL) draw_info->stroke_pattern=DestroyImage( draw_info->stroke_pattern); break; } sans=AcquireExceptionInfo(); status=QueryColorCompliance(argv[i+1],AllCompliance,&color,sans); sans=DestroyExceptionInfo(sans); if (status == MagickFalse) draw_info->stroke_pattern=GetImageCache(mogrify_info,argv[i+1], exception); else draw_info->stroke=color; break; } if (LocaleCompare(\"strokewidth\",option+1) == 0) { draw_info->stroke_width=StringToDouble(argv[i+1],(char **) NULL); break; } if (LocaleCompare(\"style\",option+1) == 0) { if (*option == '+') { draw_info->style=UndefinedStyle; break; } draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"swirl\",option+1) == 0) { \/* Swirl image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=SwirlImage(*image,geometry_info.rho, interpolate_method,exception); break; } break; } case 't': { if (LocaleCompare(\"threshold\",option+1) == 0) { double threshold; \/* Threshold image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') threshold=(double) QuantumRange\/2; else threshold=StringToDoubleInterval(argv[i+1],(double) QuantumRange+ 1.0); (void) BilevelImage(*image,threshold,exception); break; } if (LocaleCompare(\"thumbnail\",option+1) == 0) { \/* Thumbnail image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ThumbnailImage(*image,geometry.width,geometry.height, exception); break; } if (LocaleCompare(\"tile\",option+1) == 0) { if (*option == '+') { if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); break; } draw_info->fill_pattern=GetImageCache(mogrify_info,argv[i+1], exception); break; } if (LocaleCompare(\"tint\",option+1) == 0) { \/* Tint the image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=TintImage(*image,argv[i+1],&fill,exception); break; } if (LocaleCompare(\"transform\",option+1) == 0) { \/* Affine transform image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=AffineTransformImage(*image,&draw_info->affine, exception); break; } if (LocaleCompare(\"transparent\",option+1) == 0) { PixelInfo target; (void) SyncImageSettings(mogrify_info,*image,exception); (void) QueryColorCompliance(argv[i+1],AllCompliance,&target, exception); (void) TransparentPaintImage(*image,&target,(Quantum) TransparentAlpha,*option == '-' ? MagickFalse : MagickTrue, exception); break; } if (LocaleCompare(\"transpose\",option+1) == 0) { \/* Transpose image scanlines. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=TransposeImage(*image,exception); break; } if (LocaleCompare(\"transverse\",option+1) == 0) { \/* Transverse image scanlines. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=TransverseImage(*image,exception); break; } if (LocaleCompare(\"treedepth\",option+1) == 0) { quantize_info->tree_depth=StringToUnsignedLong(argv[i+1]); break; } if (LocaleCompare(\"trim\",option+1) == 0) { \/* Trim image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=TrimImage(*image,exception); break; } if (LocaleCompare(\"type\",option+1) == 0) { ImageType type; (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') type=UndefinedType; else type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse, argv[i+1]); (*image)->type=UndefinedType; (void) SetImageType(*image,type,exception); break; } break; } case 'u': { if (LocaleCompare(\"undercolor\",option+1) == 0) { (void) QueryColorCompliance(argv[i+1],AllCompliance, &draw_info->undercolor,exception); break; } if (LocaleCompare(\"unique\",option+1) == 0) { if (*option == '+') { (void) DeleteImageArtifact(*image,\"identify:unique-colors\"); break; } (void) SetImageArtifact(*image,\"identify:unique-colors\",\"true\"); (void) SetImageArtifact(*image,\"verbose\",\"true\"); break; } if (LocaleCompare(\"unique-colors\",option+1) == 0) { \/* Unique image colors. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); mogrify_image=UniqueImageColors(*image,exception); break; } if (LocaleCompare(\"unsharp\",option+1) == 0) { \/* Unsharp mask image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=1.0; if ((flags & PsiValue) == 0) geometry_info.psi=0.05; mogrify_image=UnsharpMaskImage(*image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,geometry_info.psi, exception); break; } break; } case 'v': { if (LocaleCompare(\"verbose\",option+1) == 0) { (void) SetImageArtifact(*image,option+1, *option == '+' ? \"false\" : \"true\"); break; } if (LocaleCompare(\"vignette\",option+1) == 0) { \/* Vignette image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=0.1*(*image)->columns; if ((flags & PsiValue) == 0) geometry_info.psi=0.1*(*image)->rows; if ((flags & PercentValue) != 0) { geometry_info.xi*=(double) (*image)->columns\/100.0; geometry_info.psi*=(double) (*image)->rows\/100.0; } mogrify_image=VignetteImage(*image,geometry_info.rho, geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5), (ssize_t) ceil(geometry_info.psi-0.5),exception); break; } if (LocaleCompare(\"virtual-pixel\",option+1) == 0) { if (*option == '+') { (void) SetImageVirtualPixelMethod(*image, UndefinedVirtualPixelMethod,exception); break; } (void) SetImageVirtualPixelMethod(*image,(VirtualPixelMethod) ParseCommandOption(MagickVirtualPixelOptions,MagickFalse, argv[i+1]),exception); break; } break; } case 'w': { if (LocaleCompare(\"wave\",option+1) == 0) { \/* Wave image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=WaveImage(*image,geometry_info.rho, geometry_info.sigma,interpolate_method,exception); break; } if (LocaleCompare(\"wavelet-denoise\",option+1) == 0) { \/* Wavelet denoise image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & PercentValue) != 0) { geometry_info.rho=QuantumRange*geometry_info.rho\/100.0; geometry_info.sigma=QuantumRange*geometry_info.sigma\/100.0; } if ((flags & SigmaValue) == 0) geometry_info.sigma=0.0; mogrify_image=WaveletDenoiseImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"weight\",option+1) == 0) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse, argv[i+1]); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(argv[i+1]); draw_info->weight=(size_t) weight; break; } if (LocaleCompare(\"white-threshold\",option+1) == 0) { \/* White threshold image. *\/ (void) SyncImageSettings(mogrify_info,*image,exception); (void) WhiteThresholdImage(*image,argv[i+1],exception); break; } if (LocaleCompare(\"write-mask\",option+1) == 0) { Image *mask; (void) SyncImageSettings(mogrify_info,*image,exception); if (*option == '+') { \/* Remove a mask. *\/ (void) SetImageMask(*image,WritePixelMask,(Image *) NULL, exception); break; } \/* Set the image mask. *\/ mask=GetImageCache(mogrify_info,argv[i+1],exception); if (mask == (Image *) NULL) break; (void) SetImageMask(*image,WritePixelMask,mask,exception); mask=DestroyImage(mask); break; } break; } default: break; } \/* Replace current image with any image that was generated *\/ if (mogrify_image != (Image *) NULL) ReplaceImageInListReturnLast(image,mogrify_image); i+=count; } \/* Free resources. *\/ quantize_info=DestroyQuantizeInfo(quantize_info); draw_info=DestroyDrawInfo(draw_info); mogrify_info=DestroyImageInfo(mogrify_info); status=(MagickStatusType) (exception->severity < ErrorException ? 1 : 0); return(status == 0 ? MagickFalse : MagickTrue); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":457053,"input":"static MagickBooleanType TransformsRGBImage(Image *image, ExceptionInfo *exception) { #define TransformsRGBImageTag \"Transform\/Image\" static const float YCCMap[1389] = { 0.000000f, 0.000720f, 0.001441f, 0.002161f, 0.002882f, 0.003602f, 0.004323f, 0.005043f, 0.005764f, 0.006484f, 0.007205f, 0.007925f, 0.008646f, 0.009366f, 0.010086f, 0.010807f, 0.011527f, 0.012248f, 0.012968f, 0.013689f, 0.014409f, 0.015130f, 0.015850f, 0.016571f, 0.017291f, 0.018012f, 0.018732f, 0.019452f, 0.020173f, 0.020893f, 0.021614f, 0.022334f, 0.023055f, 0.023775f, 0.024496f, 0.025216f, 0.025937f, 0.026657f, 0.027378f, 0.028098f, 0.028818f, 0.029539f, 0.030259f, 0.030980f, 0.031700f, 0.032421f, 0.033141f, 0.033862f, 0.034582f, 0.035303f, 0.036023f, 0.036744f, 0.037464f, 0.038184f, 0.038905f, 0.039625f, 0.040346f, 0.041066f, 0.041787f, 0.042507f, 0.043228f, 0.043948f, 0.044669f, 0.045389f, 0.046110f, 0.046830f, 0.047550f, 0.048271f, 0.048991f, 0.049712f, 0.050432f, 0.051153f, 0.051873f, 0.052594f, 0.053314f, 0.054035f, 0.054755f, 0.055476f, 0.056196f, 0.056916f, 0.057637f, 0.058357f, 0.059078f, 0.059798f, 0.060519f, 0.061239f, 0.061960f, 0.062680f, 0.063401f, 0.064121f, 0.064842f, 0.065562f, 0.066282f, 0.067003f, 0.067723f, 0.068444f, 0.069164f, 0.069885f, 0.070605f, 0.071326f, 0.072046f, 0.072767f, 0.073487f, 0.074207f, 0.074928f, 0.075648f, 0.076369f, 0.077089f, 0.077810f, 0.078530f, 0.079251f, 0.079971f, 0.080692f, 0.081412f, 0.082133f, 0.082853f, 0.083573f, 0.084294f, 0.085014f, 0.085735f, 0.086455f, 0.087176f, 0.087896f, 0.088617f, 0.089337f, 0.090058f, 0.090778f, 0.091499f, 0.092219f, 0.092939f, 0.093660f, 0.094380f, 0.095101f, 0.095821f, 0.096542f, 0.097262f, 0.097983f, 0.098703f, 0.099424f, 0.100144f, 0.100865f, 0.101585f, 0.102305f, 0.103026f, 0.103746f, 0.104467f, 0.105187f, 0.105908f, 0.106628f, 0.107349f, 0.108069f, 0.108790f, 0.109510f, 0.110231f, 0.110951f, 0.111671f, 0.112392f, 0.113112f, 0.113833f, 0.114553f, 0.115274f, 0.115994f, 0.116715f, 0.117435f, 0.118156f, 0.118876f, 0.119597f, 0.120317f, 0.121037f, 0.121758f, 0.122478f, 0.123199f, 0.123919f, 0.124640f, 0.125360f, 0.126081f, 0.126801f, 0.127522f, 0.128242f, 0.128963f, 0.129683f, 0.130403f, 0.131124f, 0.131844f, 0.132565f, 0.133285f, 0.134006f, 0.134726f, 0.135447f, 0.136167f, 0.136888f, 0.137608f, 0.138329f, 0.139049f, 0.139769f, 0.140490f, 0.141210f, 0.141931f, 0.142651f, 0.143372f, 0.144092f, 0.144813f, 0.145533f, 0.146254f, 0.146974f, 0.147695f, 0.148415f, 0.149135f, 0.149856f, 0.150576f, 0.151297f, 0.152017f, 0.152738f, 0.153458f, 0.154179f, 0.154899f, 0.155620f, 0.156340f, 0.157061f, 0.157781f, 0.158501f, 0.159222f, 0.159942f, 0.160663f, 0.161383f, 0.162104f, 0.162824f, 0.163545f, 0.164265f, 0.164986f, 0.165706f, 0.166427f, 0.167147f, 0.167867f, 0.168588f, 0.169308f, 0.170029f, 0.170749f, 0.171470f, 0.172190f, 0.172911f, 0.173631f, 0.174352f, 0.175072f, 0.175793f, 0.176513f, 0.177233f, 0.177954f, 0.178674f, 0.179395f, 0.180115f, 0.180836f, 0.181556f, 0.182277f, 0.182997f, 0.183718f, 0.184438f, 0.185159f, 0.185879f, 0.186599f, 0.187320f, 0.188040f, 0.188761f, 0.189481f, 0.190202f, 0.190922f, 0.191643f, 0.192363f, 0.193084f, 0.193804f, 0.194524f, 0.195245f, 0.195965f, 0.196686f, 0.197406f, 0.198127f, 0.198847f, 0.199568f, 0.200288f, 0.201009f, 0.201729f, 0.202450f, 0.203170f, 0.203890f, 0.204611f, 0.205331f, 0.206052f, 0.206772f, 0.207493f, 0.208213f, 0.208934f, 0.209654f, 0.210375f, 0.211095f, 0.211816f, 0.212536f, 0.213256f, 0.213977f, 0.214697f, 0.215418f, 0.216138f, 0.216859f, 0.217579f, 0.218300f, 0.219020f, 0.219741f, 0.220461f, 0.221182f, 0.221902f, 0.222622f, 0.223343f, 0.224063f, 0.224784f, 0.225504f, 0.226225f, 0.226945f, 0.227666f, 0.228386f, 0.229107f, 0.229827f, 0.230548f, 0.231268f, 0.231988f, 0.232709f, 0.233429f, 0.234150f, 0.234870f, 0.235591f, 0.236311f, 0.237032f, 0.237752f, 0.238473f, 0.239193f, 0.239914f, 0.240634f, 0.241354f, 0.242075f, 0.242795f, 0.243516f, 0.244236f, 0.244957f, 0.245677f, 0.246398f, 0.247118f, 0.247839f, 0.248559f, 0.249280f, 0.250000f, 0.250720f, 0.251441f, 0.252161f, 0.252882f, 0.253602f, 0.254323f, 0.255043f, 0.255764f, 0.256484f, 0.257205f, 0.257925f, 0.258646f, 0.259366f, 0.260086f, 0.260807f, 0.261527f, 0.262248f, 0.262968f, 0.263689f, 0.264409f, 0.265130f, 0.265850f, 0.266571f, 0.267291f, 0.268012f, 0.268732f, 0.269452f, 0.270173f, 0.270893f, 0.271614f, 0.272334f, 0.273055f, 0.273775f, 0.274496f, 0.275216f, 0.275937f, 0.276657f, 0.277378f, 0.278098f, 0.278818f, 0.279539f, 0.280259f, 0.280980f, 0.281700f, 0.282421f, 0.283141f, 0.283862f, 0.284582f, 0.285303f, 0.286023f, 0.286744f, 0.287464f, 0.288184f, 0.288905f, 0.289625f, 0.290346f, 0.291066f, 0.291787f, 0.292507f, 0.293228f, 0.293948f, 0.294669f, 0.295389f, 0.296109f, 0.296830f, 0.297550f, 0.298271f, 0.298991f, 0.299712f, 0.300432f, 0.301153f, 0.301873f, 0.302594f, 0.303314f, 0.304035f, 0.304755f, 0.305476f, 0.306196f, 0.306916f, 0.307637f, 0.308357f, 0.309078f, 0.309798f, 0.310519f, 0.311239f, 0.311960f, 0.312680f, 0.313401f, 0.314121f, 0.314842f, 0.315562f, 0.316282f, 0.317003f, 0.317723f, 0.318444f, 0.319164f, 0.319885f, 0.320605f, 0.321326f, 0.322046f, 0.322767f, 0.323487f, 0.324207f, 0.324928f, 0.325648f, 0.326369f, 0.327089f, 0.327810f, 0.328530f, 0.329251f, 0.329971f, 0.330692f, 0.331412f, 0.332133f, 0.332853f, 0.333573f, 0.334294f, 0.335014f, 0.335735f, 0.336455f, 0.337176f, 0.337896f, 0.338617f, 0.339337f, 0.340058f, 0.340778f, 0.341499f, 0.342219f, 0.342939f, 0.343660f, 0.344380f, 0.345101f, 0.345821f, 0.346542f, 0.347262f, 0.347983f, 0.348703f, 0.349424f, 0.350144f, 0.350865f, 0.351585f, 0.352305f, 0.353026f, 0.353746f, 0.354467f, 0.355187f, 0.355908f, 0.356628f, 0.357349f, 0.358069f, 0.358790f, 0.359510f, 0.360231f, 0.360951f, 0.361671f, 0.362392f, 0.363112f, 0.363833f, 0.364553f, 0.365274f, 0.365994f, 0.366715f, 0.367435f, 0.368156f, 0.368876f, 0.369597f, 0.370317f, 0.371037f, 0.371758f, 0.372478f, 0.373199f, 0.373919f, 0.374640f, 0.375360f, 0.376081f, 0.376801f, 0.377522f, 0.378242f, 0.378963f, 0.379683f, 0.380403f, 0.381124f, 0.381844f, 0.382565f, 0.383285f, 0.384006f, 0.384726f, 0.385447f, 0.386167f, 0.386888f, 0.387608f, 0.388329f, 0.389049f, 0.389769f, 0.390490f, 0.391210f, 0.391931f, 0.392651f, 0.393372f, 0.394092f, 0.394813f, 0.395533f, 0.396254f, 0.396974f, 0.397695f, 0.398415f, 0.399135f, 0.399856f, 0.400576f, 0.401297f, 0.402017f, 0.402738f, 0.403458f, 0.404179f, 0.404899f, 0.405620f, 0.406340f, 0.407061f, 0.407781f, 0.408501f, 0.409222f, 0.409942f, 0.410663f, 0.411383f, 0.412104f, 0.412824f, 0.413545f, 0.414265f, 0.414986f, 0.415706f, 0.416427f, 0.417147f, 0.417867f, 0.418588f, 0.419308f, 0.420029f, 0.420749f, 0.421470f, 0.422190f, 0.422911f, 0.423631f, 0.424352f, 0.425072f, 0.425793f, 0.426513f, 0.427233f, 0.427954f, 0.428674f, 0.429395f, 0.430115f, 0.430836f, 0.431556f, 0.432277f, 0.432997f, 0.433718f, 0.434438f, 0.435158f, 0.435879f, 0.436599f, 0.437320f, 0.438040f, 0.438761f, 0.439481f, 0.440202f, 0.440922f, 0.441643f, 0.442363f, 0.443084f, 0.443804f, 0.444524f, 0.445245f, 0.445965f, 0.446686f, 0.447406f, 0.448127f, 0.448847f, 0.449568f, 0.450288f, 0.451009f, 0.451729f, 0.452450f, 0.453170f, 0.453891f, 0.454611f, 0.455331f, 0.456052f, 0.456772f, 0.457493f, 0.458213f, 0.458934f, 0.459654f, 0.460375f, 0.461095f, 0.461816f, 0.462536f, 0.463256f, 0.463977f, 0.464697f, 0.465418f, 0.466138f, 0.466859f, 0.467579f, 0.468300f, 0.469020f, 0.469741f, 0.470461f, 0.471182f, 0.471902f, 0.472622f, 0.473343f, 0.474063f, 0.474784f, 0.475504f, 0.476225f, 0.476945f, 0.477666f, 0.478386f, 0.479107f, 0.479827f, 0.480548f, 0.481268f, 0.481988f, 0.482709f, 0.483429f, 0.484150f, 0.484870f, 0.485591f, 0.486311f, 0.487032f, 0.487752f, 0.488473f, 0.489193f, 0.489914f, 0.490634f, 0.491354f, 0.492075f, 0.492795f, 0.493516f, 0.494236f, 0.494957f, 0.495677f, 0.496398f, 0.497118f, 0.497839f, 0.498559f, 0.499280f, 0.500000f, 0.500720f, 0.501441f, 0.502161f, 0.502882f, 0.503602f, 0.504323f, 0.505043f, 0.505764f, 0.506484f, 0.507205f, 0.507925f, 0.508646f, 0.509366f, 0.510086f, 0.510807f, 0.511527f, 0.512248f, 0.512968f, 0.513689f, 0.514409f, 0.515130f, 0.515850f, 0.516571f, 0.517291f, 0.518012f, 0.518732f, 0.519452f, 0.520173f, 0.520893f, 0.521614f, 0.522334f, 0.523055f, 0.523775f, 0.524496f, 0.525216f, 0.525937f, 0.526657f, 0.527378f, 0.528098f, 0.528818f, 0.529539f, 0.530259f, 0.530980f, 0.531700f, 0.532421f, 0.533141f, 0.533862f, 0.534582f, 0.535303f, 0.536023f, 0.536744f, 0.537464f, 0.538184f, 0.538905f, 0.539625f, 0.540346f, 0.541066f, 0.541787f, 0.542507f, 0.543228f, 0.543948f, 0.544669f, 0.545389f, 0.546109f, 0.546830f, 0.547550f, 0.548271f, 0.548991f, 0.549712f, 0.550432f, 0.551153f, 0.551873f, 0.552594f, 0.553314f, 0.554035f, 0.554755f, 0.555476f, 0.556196f, 0.556916f, 0.557637f, 0.558357f, 0.559078f, 0.559798f, 0.560519f, 0.561239f, 0.561960f, 0.562680f, 0.563401f, 0.564121f, 0.564842f, 0.565562f, 0.566282f, 0.567003f, 0.567723f, 0.568444f, 0.569164f, 0.569885f, 0.570605f, 0.571326f, 0.572046f, 0.572767f, 0.573487f, 0.574207f, 0.574928f, 0.575648f, 0.576369f, 0.577089f, 0.577810f, 0.578530f, 0.579251f, 0.579971f, 0.580692f, 0.581412f, 0.582133f, 0.582853f, 0.583573f, 0.584294f, 0.585014f, 0.585735f, 0.586455f, 0.587176f, 0.587896f, 0.588617f, 0.589337f, 0.590058f, 0.590778f, 0.591499f, 0.592219f, 0.592939f, 0.593660f, 0.594380f, 0.595101f, 0.595821f, 0.596542f, 0.597262f, 0.597983f, 0.598703f, 0.599424f, 0.600144f, 0.600865f, 0.601585f, 0.602305f, 0.603026f, 0.603746f, 0.604467f, 0.605187f, 0.605908f, 0.606628f, 0.607349f, 0.608069f, 0.608790f, 0.609510f, 0.610231f, 0.610951f, 0.611671f, 0.612392f, 0.613112f, 0.613833f, 0.614553f, 0.615274f, 0.615994f, 0.616715f, 0.617435f, 0.618156f, 0.618876f, 0.619597f, 0.620317f, 0.621037f, 0.621758f, 0.622478f, 0.623199f, 0.623919f, 0.624640f, 0.625360f, 0.626081f, 0.626801f, 0.627522f, 0.628242f, 0.628963f, 0.629683f, 0.630403f, 0.631124f, 0.631844f, 0.632565f, 0.633285f, 0.634006f, 0.634726f, 0.635447f, 0.636167f, 0.636888f, 0.637608f, 0.638329f, 0.639049f, 0.639769f, 0.640490f, 0.641210f, 0.641931f, 0.642651f, 0.643372f, 0.644092f, 0.644813f, 0.645533f, 0.646254f, 0.646974f, 0.647695f, 0.648415f, 0.649135f, 0.649856f, 0.650576f, 0.651297f, 0.652017f, 0.652738f, 0.653458f, 0.654179f, 0.654899f, 0.655620f, 0.656340f, 0.657061f, 0.657781f, 0.658501f, 0.659222f, 0.659942f, 0.660663f, 0.661383f, 0.662104f, 0.662824f, 0.663545f, 0.664265f, 0.664986f, 0.665706f, 0.666427f, 0.667147f, 0.667867f, 0.668588f, 0.669308f, 0.670029f, 0.670749f, 0.671470f, 0.672190f, 0.672911f, 0.673631f, 0.674352f, 0.675072f, 0.675793f, 0.676513f, 0.677233f, 0.677954f, 0.678674f, 0.679395f, 0.680115f, 0.680836f, 0.681556f, 0.682277f, 0.682997f, 0.683718f, 0.684438f, 0.685158f, 0.685879f, 0.686599f, 0.687320f, 0.688040f, 0.688761f, 0.689481f, 0.690202f, 0.690922f, 0.691643f, 0.692363f, 0.693084f, 0.693804f, 0.694524f, 0.695245f, 0.695965f, 0.696686f, 0.697406f, 0.698127f, 0.698847f, 0.699568f, 0.700288f, 0.701009f, 0.701729f, 0.702450f, 0.703170f, 0.703891f, 0.704611f, 0.705331f, 0.706052f, 0.706772f, 0.707493f, 0.708213f, 0.708934f, 0.709654f, 0.710375f, 0.711095f, 0.711816f, 0.712536f, 0.713256f, 0.713977f, 0.714697f, 0.715418f, 0.716138f, 0.716859f, 0.717579f, 0.718300f, 0.719020f, 0.719741f, 0.720461f, 0.721182f, 0.721902f, 0.722622f, 0.723343f, 0.724063f, 0.724784f, 0.725504f, 0.726225f, 0.726945f, 0.727666f, 0.728386f, 0.729107f, 0.729827f, 0.730548f, 0.731268f, 0.731988f, 0.732709f, 0.733429f, 0.734150f, 0.734870f, 0.735591f, 0.736311f, 0.737032f, 0.737752f, 0.738473f, 0.739193f, 0.739914f, 0.740634f, 0.741354f, 0.742075f, 0.742795f, 0.743516f, 0.744236f, 0.744957f, 0.745677f, 0.746398f, 0.747118f, 0.747839f, 0.748559f, 0.749280f, 0.750000f, 0.750720f, 0.751441f, 0.752161f, 0.752882f, 0.753602f, 0.754323f, 0.755043f, 0.755764f, 0.756484f, 0.757205f, 0.757925f, 0.758646f, 0.759366f, 0.760086f, 0.760807f, 0.761527f, 0.762248f, 0.762968f, 0.763689f, 0.764409f, 0.765130f, 0.765850f, 0.766571f, 0.767291f, 0.768012f, 0.768732f, 0.769452f, 0.770173f, 0.770893f, 0.771614f, 0.772334f, 0.773055f, 0.773775f, 0.774496f, 0.775216f, 0.775937f, 0.776657f, 0.777378f, 0.778098f, 0.778818f, 0.779539f, 0.780259f, 0.780980f, 0.781700f, 0.782421f, 0.783141f, 0.783862f, 0.784582f, 0.785303f, 0.786023f, 0.786744f, 0.787464f, 0.788184f, 0.788905f, 0.789625f, 0.790346f, 0.791066f, 0.791787f, 0.792507f, 0.793228f, 0.793948f, 0.794669f, 0.795389f, 0.796109f, 0.796830f, 0.797550f, 0.798271f, 0.798991f, 0.799712f, 0.800432f, 0.801153f, 0.801873f, 0.802594f, 0.803314f, 0.804035f, 0.804755f, 0.805476f, 0.806196f, 0.806916f, 0.807637f, 0.808357f, 0.809078f, 0.809798f, 0.810519f, 0.811239f, 0.811960f, 0.812680f, 0.813401f, 0.814121f, 0.814842f, 0.815562f, 0.816282f, 0.817003f, 0.817723f, 0.818444f, 0.819164f, 0.819885f, 0.820605f, 0.821326f, 0.822046f, 0.822767f, 0.823487f, 0.824207f, 0.824928f, 0.825648f, 0.826369f, 0.827089f, 0.827810f, 0.828530f, 0.829251f, 0.829971f, 0.830692f, 0.831412f, 0.832133f, 0.832853f, 0.833573f, 0.834294f, 0.835014f, 0.835735f, 0.836455f, 0.837176f, 0.837896f, 0.838617f, 0.839337f, 0.840058f, 0.840778f, 0.841499f, 0.842219f, 0.842939f, 0.843660f, 0.844380f, 0.845101f, 0.845821f, 0.846542f, 0.847262f, 0.847983f, 0.848703f, 0.849424f, 0.850144f, 0.850865f, 0.851585f, 0.852305f, 0.853026f, 0.853746f, 0.854467f, 0.855187f, 0.855908f, 0.856628f, 0.857349f, 0.858069f, 0.858790f, 0.859510f, 0.860231f, 0.860951f, 0.861671f, 0.862392f, 0.863112f, 0.863833f, 0.864553f, 0.865274f, 0.865994f, 0.866715f, 0.867435f, 0.868156f, 0.868876f, 0.869597f, 0.870317f, 0.871037f, 0.871758f, 0.872478f, 0.873199f, 0.873919f, 0.874640f, 0.875360f, 0.876081f, 0.876801f, 0.877522f, 0.878242f, 0.878963f, 0.879683f, 0.880403f, 0.881124f, 0.881844f, 0.882565f, 0.883285f, 0.884006f, 0.884726f, 0.885447f, 0.886167f, 0.886888f, 0.887608f, 0.888329f, 0.889049f, 0.889769f, 0.890490f, 0.891210f, 0.891931f, 0.892651f, 0.893372f, 0.894092f, 0.894813f, 0.895533f, 0.896254f, 0.896974f, 0.897695f, 0.898415f, 0.899135f, 0.899856f, 0.900576f, 0.901297f, 0.902017f, 0.902738f, 0.903458f, 0.904179f, 0.904899f, 0.905620f, 0.906340f, 0.907061f, 0.907781f, 0.908501f, 0.909222f, 0.909942f, 0.910663f, 0.911383f, 0.912104f, 0.912824f, 0.913545f, 0.914265f, 0.914986f, 0.915706f, 0.916427f, 0.917147f, 0.917867f, 0.918588f, 0.919308f, 0.920029f, 0.920749f, 0.921470f, 0.922190f, 0.922911f, 0.923631f, 0.924352f, 0.925072f, 0.925793f, 0.926513f, 0.927233f, 0.927954f, 0.928674f, 0.929395f, 0.930115f, 0.930836f, 0.931556f, 0.932277f, 0.932997f, 0.933718f, 0.934438f, 0.935158f, 0.935879f, 0.936599f, 0.937320f, 0.938040f, 0.938761f, 0.939481f, 0.940202f, 0.940922f, 0.941643f, 0.942363f, 0.943084f, 0.943804f, 0.944524f, 0.945245f, 0.945965f, 0.946686f, 0.947406f, 0.948127f, 0.948847f, 0.949568f, 0.950288f, 0.951009f, 0.951729f, 0.952450f, 0.953170f, 0.953891f, 0.954611f, 0.955331f, 0.956052f, 0.956772f, 0.957493f, 0.958213f, 0.958934f, 0.959654f, 0.960375f, 0.961095f, 0.961816f, 0.962536f, 0.963256f, 0.963977f, 0.964697f, 0.965418f, 0.966138f, 0.966859f, 0.967579f, 0.968300f, 0.969020f, 0.969741f, 0.970461f, 0.971182f, 0.971902f, 0.972622f, 0.973343f, 0.974063f, 0.974784f, 0.975504f, 0.976225f, 0.976945f, 0.977666f, 0.978386f, 0.979107f, 0.979827f, 0.980548f, 0.981268f, 0.981988f, 0.982709f, 0.983429f, 0.984150f, 0.984870f, 0.985591f, 0.986311f, 0.987032f, 0.987752f, 0.988473f, 0.989193f, 0.989914f, 0.990634f, 0.991354f, 0.992075f, 0.992795f, 0.993516f, 0.994236f, 0.994957f, 0.995677f, 0.996398f, 0.997118f, 0.997839f, 0.998559f, 0.999280f, 1.000000f }; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; TransformPacket *y_map, *x_map, *z_map; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); status=MagickTrue; progress=0; switch (image->colorspace) { case CMYKColorspace: { PixelInfo zero; \/* Transform image from CMYK to sRGB. *\/ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \\ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); ConvertCMYKToRGB(&pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case LinearGRAYColorspace: { \/* Transform linear GRAY to sRGB colorspace. *\/ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \\ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=(ssize_t) image->columns; x != 0; x--) { MagickRealType gray; gray=0.212656*GetPixelRed(image,q)+0.715158*GetPixelGreen(image,q)+ 0.072186*GetPixelBlue(image,q); gray=EncodePixelGamma(gray); SetPixelRed(image,ClampToQuantum(gray),q); SetPixelGreen(image,ClampToQuantum(gray),q); SetPixelBlue(image,ClampToQuantum(gray),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case GRAYColorspace: { \/* Transform linear GRAY to sRGB colorspace. *\/ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \\ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=(ssize_t) image->columns; x != 0; x--) { MagickRealType gray; gray=0.212656*GetPixelRed(image,q)+0.715158*GetPixelGreen(image,q)+ 0.072186*GetPixelBlue(image,q); SetPixelRed(image,ClampToQuantum(gray),q); SetPixelGreen(image,ClampToQuantum(gray),q); SetPixelBlue(image,ClampToQuantum(gray),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case Adobe98Colorspace: case CMYColorspace: case DisplayP3Colorspace: case HCLColorspace: case HCLpColorspace: case HSBColorspace: case HSIColorspace: case HSLColorspace: case HSVColorspace: case HWBColorspace: case JzazbzColorspace: case LabColorspace: case LCHColorspace: case LCHabColorspace: case LCHuvColorspace: case LMSColorspace: case LuvColorspace: case ProPhotoColorspace: case xyYColorspace: case XYZColorspace: case YCbCrColorspace: case YDbDrColorspace: case YIQColorspace: case YPbPrColorspace: case YUVColorspace: { const char *value; double white_luminance; \/* Transform image from source colorspace to sRGB. *\/ white_luminance=10000.0; value=GetImageProperty(image,\"white-luminance\",exception); if (value != (const char *) NULL) white_luminance=StringToDouble(value,(char **) NULL); if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \\ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red, X, Y, Z; X=QuantumScale*GetPixelRed(image,q); Y=QuantumScale*GetPixelGreen(image,q); Z=QuantumScale*GetPixelBlue(image,q); switch (image->colorspace) { case Adobe98Colorspace: { ConvertAdobe98ToRGB(X,Y,Z,&red,&green,&blue); break; } case CMYColorspace: { ConvertCMYToRGB(X,Y,Z,&red,&green,&blue); break; } case DisplayP3Colorspace: { ConvertDisplayP3ToRGB(X,Y,Z,&red,&green,&blue); break; } case HCLColorspace: { ConvertHCLToRGB(X,Y,Z,&red,&green,&blue); break; } case HCLpColorspace: { ConvertHCLpToRGB(X,Y,Z,&red,&green,&blue); break; } case HSBColorspace: { ConvertHSBToRGB(X,Y,Z,&red,&green,&blue); break; } case HSIColorspace: { ConvertHSIToRGB(X,Y,Z,&red,&green,&blue); break; } case HSLColorspace: { ConvertHSLToRGB(X,Y,Z,&red,&green,&blue); break; } case HSVColorspace: { ConvertHSVToRGB(X,Y,Z,&red,&green,&blue); break; } case HWBColorspace: { ConvertHWBToRGB(X,Y,Z,&red,&green,&blue); break; } case JzazbzColorspace: { ConvertJzazbzToRGB(X,Y,Z,white_luminance,&red,&green,&blue); break; } case LabColorspace: { ConvertLabToRGB(X,Y,Z,&red,&green,&blue); break; } case LCHColorspace: case LCHabColorspace: { ConvertLCHabToRGB(X,Y,Z,&red,&green,&blue); break; } case LCHuvColorspace: { ConvertLCHuvToRGB(X,Y,Z,&red,&green,&blue); break; } case LMSColorspace: { ConvertLMSToRGB(X,Y,Z,&red,&green,&blue); break; } case LuvColorspace: { ConvertLuvToRGB(X,Y,Z,&red,&green,&blue); break; } case ProPhotoColorspace: { ConvertProPhotoToRGB(X,Y,Z,&red,&green,&blue); break; } case xyYColorspace: { ConvertxyYToRGB(X,Y,Z,&red,&green,&blue); break; } case XYZColorspace: { ConvertXYZToRGB(X,Y,Z,&red,&green,&blue); break; } case YCbCrColorspace: { ConvertYCbCrToRGB(X,Y,Z,&red,&green,&blue); break; } case YDbDrColorspace: { ConvertYDbDrToRGB(X,Y,Z,&red,&green,&blue); break; } case YIQColorspace: { ConvertYIQToRGB(X,Y,Z,&red,&green,&blue); break; } case YPbPrColorspace: { ConvertYPbPrToRGB(X,Y,Z,&red,&green,&blue); break; } case YUVColorspace: { ConvertYUVToRGB(X,Y,Z,&red,&green,&blue); break; } default: { red=QuantumRange*X; green=QuantumRange*Y; blue=QuantumRange*Z; break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case LogColorspace: { const char *value; double black, density, film_gamma, gamma, reference_black, reference_white; Quantum *logmap; \/* Transform Log to sRGB colorspace. *\/ density=DisplayGamma; gamma=DisplayGamma; value=GetImageProperty(image,\"gamma\",exception); if (value != (const char *) NULL) gamma=PerceptibleReciprocal(StringToDouble(value,(char **) NULL)); film_gamma=FilmGamma; value=GetImageProperty(image,\"film-gamma\",exception); if (value != (const char *) NULL) film_gamma=StringToDouble(value,(char **) NULL); reference_black=ReferenceBlack; value=GetImageProperty(image,\"reference-black\",exception); if (value != (const char *) NULL) reference_black=StringToDouble(value,(char **) NULL); reference_white=ReferenceWhite; value=GetImageProperty(image,\"reference-white\",exception); if (value != (const char *) NULL) reference_white=StringToDouble(value,(char **) NULL); logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*logmap)); if (logmap == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\", image->filename); black=pow(10.0,(reference_black-reference_white)*(gamma\/density)*0.002* PerceptibleReciprocal(film_gamma)); for (i=0; i <= (ssize_t) (reference_black*MaxMap\/1024.0); i++) logmap[i]=(Quantum) 0; for ( ; i < (ssize_t) (reference_white*MaxMap\/1024.0); i++) logmap[i]=ClampToQuantum(QuantumRange\/(1.0-black)* (pow(10.0,(1024.0*i\/MaxMap-reference_white)*(gamma\/density)*0.002* PerceptibleReciprocal(film_gamma))-black)); for ( ; i <= (ssize_t) MaxMap; i++) logmap[i]=QuantumRange; if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \\ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=(ssize_t) image->columns; x != 0; x--) { double blue, green, red; red=(double) logmap[ScaleQuantumToMap(GetPixelRed(image,q))]; green=(double) logmap[ScaleQuantumToMap(GetPixelGreen(image,q))]; blue=(double) logmap[ScaleQuantumToMap(GetPixelBlue(image,q))]; SetPixelRed(image,ClampToQuantum(EncodePixelGamma((MagickRealType) red)),q); SetPixelGreen(image,ClampToQuantum(EncodePixelGamma((MagickRealType) green)),q); SetPixelBlue(image,ClampToQuantum(EncodePixelGamma((MagickRealType) blue)),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); logmap=(Quantum *) RelinquishMagickMemory(logmap); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case RGBColorspace: case scRGBColorspace: { \/* Transform linear RGB to sRGB colorspace. *\/ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \\ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=(ssize_t) image->columns; x != 0; x--) { double blue, green, red; red=EncodePixelGamma((MagickRealType) GetPixelRed(image,q)); green=EncodePixelGamma((MagickRealType) GetPixelGreen(image,q)); blue=EncodePixelGamma((MagickRealType) GetPixelBlue(image,q)); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } default: break; } \/* Allocate the tables. *\/ x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*x_map)); y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*y_map)); z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*z_map)); if ((x_map == (TransformPacket *) NULL) || (y_map == (TransformPacket *) NULL) || (z_map == (TransformPacket *) NULL)) { if (z_map != (TransformPacket *) NULL) z_map=(TransformPacket *) RelinquishMagickMemory(z_map); if (y_map != (TransformPacket *) NULL) y_map=(TransformPacket *) RelinquishMagickMemory(y_map); if (x_map != (TransformPacket *) NULL) x_map=(TransformPacket *) RelinquishMagickMemory(x_map); ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\", image->filename); } switch (image->colorspace) { case OHTAColorspace: { \/* Initialize OHTA tables: I1 = 0.33333*R+0.33334*G+0.33333*B I2 = 0.50000*R+0.00000*G-0.50000*B I3 =-0.25000*R+0.50000*G-0.25000*B R = I1+1.00000*I2-0.66668*I3 G = I1+0.00000*I2+1.33333*I3 B = I1-1.00000*I2-0.66668*I3 I and Q, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. *\/ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*(double) i); y_map[i].x=(MagickRealType) (0.5*1.00000*(2.0*(double) i-MaxMap)); z_map[i].x=(MagickRealType) (-0.5*0.66668*(2.0*(double) i-MaxMap)); x_map[i].y=(MagickRealType) (1.0*(double) i); y_map[i].y=(MagickRealType) (0.5*0.00000*(2.0*(double) i-MaxMap)); z_map[i].y=(MagickRealType) (0.5*1.33333*(2.0*(double) i-MaxMap)); x_map[i].z=(MagickRealType) (1.0*(double) i); y_map[i].z=(MagickRealType) (-0.5*1.00000*(2.0*(double) i-MaxMap)); z_map[i].z=(MagickRealType) (-0.5*0.66668*(2.0*(double) i-MaxMap)); } break; } case Rec601YCbCrColorspace: { \/* Initialize YCbCr tables: R = Y +1.402000*Cr G = Y-0.344136*Cb-0.714136*Cr B = Y+1.772000*Cb Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. *\/ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=0.99999999999914679361*(double) i; y_map[i].x=0.5*(-1.2188941887145875e-06)*(2.00*(double) i-MaxMap); z_map[i].x=0.5*1.4019995886561440468*(2.00*(double) i-MaxMap); x_map[i].y=0.99999975910502514331*(double) i; y_map[i].y=0.5*(-0.34413567816504303521)*(2.00*(double) i-MaxMap); z_map[i].y=0.5*(-0.71413649331646789076)*(2.00*(double) i-MaxMap); x_map[i].z=1.00000124040004623180*(double) i; y_map[i].z=0.5*1.77200006607230409200*(2.00*(double) i-MaxMap); z_map[i].z=0.5*2.1453384174593273e-06*(2.00*(double) i-MaxMap); } break; } case Rec709YCbCrColorspace: { \/* Initialize YCbCr tables: R = Y +1.574800*Cr G = Y-0.187324*Cb-0.468124*Cr B = Y+1.855600*Cb Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. *\/ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*i); y_map[i].x=(MagickRealType) (0.5*0.000000*(2.0*i-MaxMap)); z_map[i].x=(MagickRealType) (0.5*1.574800*(2.0*i-MaxMap)); x_map[i].y=(MagickRealType) (1.0*i); y_map[i].y=(MagickRealType) (0.5*(-0.187324)*(2.0*i-MaxMap)); z_map[i].y=(MagickRealType) (0.5*(-0.468124)*(2.0*i-MaxMap)); x_map[i].z=(MagickRealType) (1.0*i); y_map[i].z=(MagickRealType) (0.5*1.855600*(2.0*i-MaxMap)); z_map[i].z=(MagickRealType) (0.5*0.000000*(2.0*i-MaxMap)); } break; } case YCCColorspace: { \/* Initialize YCC tables: R = Y +1.340762*C2 G = Y-0.317038*C1-0.682243*C2 B = Y+1.632639*C1 YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137. *\/ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.3584000*(double) i); y_map[i].x=(MagickRealType) 0.0000000; z_map[i].x=(MagickRealType) (1.8215000*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(137)))); x_map[i].y=(MagickRealType) (1.3584000*(double) i); y_map[i].y=(MagickRealType) (-0.4302726*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(156)))); z_map[i].y=(MagickRealType) (-0.9271435*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(137)))); x_map[i].z=(MagickRealType) (1.3584000*(double) i); y_map[i].z=(MagickRealType) (2.2179000*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(156)))); z_map[i].z=(MagickRealType) 0.0000000; } break; } default: { \/* Linear conversion tables. *\/ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*(double) i); y_map[i].x=(MagickRealType) 0.0; z_map[i].x=(MagickRealType) 0.0; x_map[i].y=(MagickRealType) 0.0; y_map[i].y=(MagickRealType) (1.0*(double) i); z_map[i].y=(MagickRealType) 0.0; x_map[i].z=(MagickRealType) 0.0; y_map[i].z=(MagickRealType) 0.0; z_map[i].z=(MagickRealType) (1.0*(double) i); } break; } } \/* Convert to sRGB. *\/ switch (image->storage_class) { case DirectClass: default: { \/* Convert DirectClass image. *\/ image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \\ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { size_t blue, green, red; red=ScaleQuantumToMap(GetPixelRed(image,q)); green=ScaleQuantumToMap(GetPixelGreen(image,q)); blue=ScaleQuantumToMap(GetPixelBlue(image,q)); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z; if (image->colorspace == YCCColorspace) { pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red\/ (double) MaxMap)]; pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green\/ (double) MaxMap)]; pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue\/ (double) MaxMap)]; } else { pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red); pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green); pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue); } SetPixelRed(image,ClampToQuantum(pixel.red),q); SetPixelGreen(image,ClampToQuantum(pixel.green),q); SetPixelBlue(image,ClampToQuantum(pixel.blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,TransformsRGBImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); break; } case PseudoClass: { \/* Convert PseudoClass image. *\/ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \\ magick_number_threads(image,image,image->rows,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { PixelInfo pixel; size_t blue, green, red; red=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red)); green=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green)); blue=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue)); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z; if (image->colorspace == YCCColorspace) { pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red\/ (double) MaxMap)]; pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green\/ (double) MaxMap)]; pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue\/ (double) MaxMap)]; } else { pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red); pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green); pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue); } image->colormap[i].red=(double) ClampToQuantum(pixel.red); image->colormap[i].green=(double) ClampToQuantum(pixel.green); image->colormap[i].blue=(double) ClampToQuantum(pixel.blue); } (void) SyncImage(image,exception); break; } } \/* Relinquish resources. *\/ z_map=(TransformPacket *) RelinquishMagickMemory(z_map); y_map=(TransformPacket *) RelinquishMagickMemory(y_map); x_map=(TransformPacket *) RelinquishMagickMemory(x_map); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(MagickTrue); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":325398,"input":"template static CImg isosurface3d(CImgList& primitives, const tfunc& func, const float isovalue, const float x0, const float y0, const float z0, const float x1, const float y1, const float z1, const int size_x=32, const int size_y=32, const int size_z=32) { static const unsigned int edges[256] = { 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 }; static const int triangles[256][16] = { { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1 }, { 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1 }, { 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1 }, { 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1 }, { 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 }, { 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1 }, { 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 }, { 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1 }, { 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1 }, { 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1 }, { 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1 }, { 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 }, { 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1 }, { 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1 }, { 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 }, { 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 }, { 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1 }, { 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1 }, { 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1 }, { 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1 }, { 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1 }, { 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1 }, { 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1 }, { 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1 }, { 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1 }, { 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1 }, { 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1 }, { 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1 }, { 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1 }, { 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1 }, { 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1 }, { 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1 }, { 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1 }, { 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1 }, { 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1 }, { 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 }, { 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1 }, { 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1 }, { 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1 }, { 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1 }, { 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1 }, { 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1 }, { 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1 }, { 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1 }, { 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1 }, { 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1 }, { 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1 }, { 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1 }, { 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1 }, { 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1 }, { 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1 }, { 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1 }, { 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1 }, { 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1 }, { 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1 }, { 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1 }, { 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1 }, { 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1 }, { 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1 }, { 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1 }, { 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1 }, { 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1 }, { 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1 }, { 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1 }, { 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1 }, { 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1 }, { 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1 }, { 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1 }, { 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1 }, { 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1 }, { 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 }, { 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 }, { 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 }, { 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1 }, { 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1 }, { 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1 }, { 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1 }, { 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1 }, { 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1 }, { 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1 }, { 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1 }, { 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1 }, { 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1 }, { 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1 }, { 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1 }, { 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1 }, { 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1 }, { 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 }, { 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1 }, { 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1 }, { 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1 }, { 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 }, { 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1 }, { 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 }, { 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1 }, { 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1 }, { 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1 }, { 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1 }, { 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1 }, { 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1 }, { 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1 }, { 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1 }, { 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1 }, { 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1 }, { 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1 }, { 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1 }, { 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1 }, { 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1 }, { 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1 }, { 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1 }, { 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1 }, { 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1 }, { 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1 }, { 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1 }, { 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1 }, { 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1 }, { 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1 }, { 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1 }, { 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1 }, { 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1 }, { 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1 }, { 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1 }, { 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1 }, { 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1 }, { 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1 }, { 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1 }, { 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1 }, { 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1 }, { 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1 }, { 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1 }, { 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1 }, { 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1 }, { 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1 }, { 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1 }, { 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1 }, { 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1 }, { 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1 }, { 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1 }, { 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1 }, { 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1 }, { 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1 }, { 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1 }, { 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1 }, { 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1 }, { 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1 }, { 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1 }, { 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1 }, { 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1 }, { 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1 }, { 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1 }, { 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1 }, { 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1 }, { 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1 }, { 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } }; const unsigned int _nx = (unsigned int)(size_x>=0?size_x:cimg::round((x1-x0)*-size_x\/100 + 1)), _ny = (unsigned int)(size_y>=0?size_y:cimg::round((y1-y0)*-size_y\/100 + 1)), _nz = (unsigned int)(size_z>=0?size_z:cimg::round((z1-z0)*-size_z\/100 + 1)), nx = _nx?_nx:1, ny = _ny?_ny:1, nz = _nz?_nz:1, nxm1 = nx - 1, nym1 = ny - 1, nzm1 = nz - 1; primitives.assign(); if (!nxm1 || !nym1 || !nzm1) return CImg(); const float dx = (x1 - x0)\/nxm1, dy = (y1 - y0)\/nym1, dz = (z1 - z0)\/nzm1; CImgList vertices; CImg indices1(nx,ny,1,3,-1), indices2(indices1); CImg values1(nx,ny), values2(nx,ny); float X = 0, Y = 0, Z = 0, nX = 0, nY = 0, nZ = 0; \/\/ Fill the first plane with function values Y = y0; cimg_forY(values1,y) { X = x0; cimg_forX(values1,x) { values1(x,y) = (float)func(X,Y,z0); X+=dx; } Y+=dy; } \/\/ Run Marching Cubes algorithm Z = z0; nZ = Z + dz; for (unsigned int zi = 0; zi::vector(Xi,Y,Z).move_to(vertices); } if ((edge&2) && indices1(nxi,yi,1)<0) { const float Yi = Y + (isovalue-val1)*dy\/(val2-val1); indices1(nxi,yi,1) = vertices.width(); CImg::vector(nX,Yi,Z).move_to(vertices); } if ((edge&4) && indices1(xi,nyi,0)<0) { const float Xi = X + (isovalue-val3)*dx\/(val2-val3); indices1(xi,nyi,0) = vertices.width(); CImg::vector(Xi,nY,Z).move_to(vertices); } if ((edge&8) && indices1(xi,yi,1)<0) { const float Yi = Y + (isovalue-val0)*dy\/(val3-val0); indices1(xi,yi,1) = vertices.width(); CImg::vector(X,Yi,Z).move_to(vertices); } if ((edge&16) && indices2(xi,yi,0)<0) { const float Xi = X + (isovalue-val4)*dx\/(val5-val4); indices2(xi,yi,0) = vertices.width(); CImg::vector(Xi,Y,nZ).move_to(vertices); } if ((edge&32) && indices2(nxi,yi,1)<0) { const float Yi = Y + (isovalue-val5)*dy\/(val6-val5); indices2(nxi,yi,1) = vertices.width(); CImg::vector(nX,Yi,nZ).move_to(vertices); } if ((edge&64) && indices2(xi,nyi,0)<0) { const float Xi = X + (isovalue-val7)*dx\/(val6-val7); indices2(xi,nyi,0) = vertices.width(); CImg::vector(Xi,nY,nZ).move_to(vertices); } if ((edge&128) && indices2(xi,yi,1)<0) { const float Yi = Y + (isovalue-val4)*dy\/(val7-val4); indices2(xi,yi,1) = vertices.width(); CImg::vector(X,Yi,nZ).move_to(vertices); } if ((edge&256) && indices1(xi,yi,2)<0) { const float Zi = Z+ (isovalue-val0)*dz\/(val4-val0); indices1(xi,yi,2) = vertices.width(); CImg::vector(X,Y,Zi).move_to(vertices); } if ((edge&512) && indices1(nxi,yi,2)<0) { const float Zi = Z + (isovalue-val1)*dz\/(val5-val1); indices1(nxi,yi,2) = vertices.width(); CImg::vector(nX,Y,Zi).move_to(vertices); } if ((edge&1024) && indices1(nxi,nyi,2)<0) { const float Zi = Z + (isovalue-val2)*dz\/(val6-val2); indices1(nxi,nyi,2) = vertices.width(); CImg::vector(nX,nY,Zi).move_to(vertices); } if ((edge&2048) && indices1(xi,nyi,2)<0) { const float Zi = Z + (isovalue-val3)*dz\/(val7-val3); indices1(xi,nyi,2) = vertices.width(); CImg::vector(X,nY,Zi).move_to(vertices); } \/\/ Create triangles for (const int *triangle = triangles[configuration]; *triangle!=-1; ) { const unsigned int p0 = (unsigned int)*(triangle++), p1 = (unsigned int)*(triangle++), p2 = (unsigned int)*(triangle++); const tf i0 = (tf)(_isosurface3d_index(p0,indices1,indices2,xi,yi,nxi,nyi)), i1 = (tf)(_isosurface3d_index(p1,indices1,indices2,xi,yi,nxi,nyi)), i2 = (tf)(_isosurface3d_index(p2,indices1,indices2,xi,yi,nxi,nyi)); CImg::vector(i0,i2,i1).move_to(primitives); } } } } cimg::swap(values1,values2); cimg::swap(indices1,indices2); } return vertices>'x';","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":10431,"input":"PHP_METHOD(Phar, webPhar) { zval *mimeoverride = NULL, *rewrite = NULL; char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL; int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0; char *fname, *path_info, *mime_type = NULL, *entry, *pt; const char *basename; int fname_len, entry_len, code, index_php_len = 0, not_cgi; phar_archive_data *phar = NULL; phar_entry_info *info = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s!s!saz\", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } return; } \/* retrieve requested file within phar *\/ if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, \"GET\") || !strcmp(SG(request_info).request_method, \"POST\")))) { return; } #ifdef PHP_WIN32 fname = estrndup(fname, fname_len); phar_unixify_path_separators(fname, fname_len); #endif basename = zend_memrchr(fname, '\/', fname_len); if (!basename) { basename = fname; } else { ++basename; } if ((strlen(sapi_module.name) == sizeof(\"cgi-fcgi\")-1 && !strncmp(sapi_module.name, \"cgi-fcgi\", sizeof(\"cgi-fcgi\")-1)) || (strlen(sapi_module.name) == sizeof(\"fpm-fcgi\")-1 && !strncmp(sapi_module.name, \"fpm-fcgi\", sizeof(\"fpm-fcgi\")-1)) || (strlen(sapi_module.name) == sizeof(\"cgi\")-1 && !strncmp(sapi_module.name, \"cgi\", sizeof(\"cgi\")-1))) { if (PG(http_globals)[TRACK_VARS_SERVER]) { HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]); zval **z_script_name, **z_path_info; if (SUCCESS != zend_hash_find(_server, \"SCRIPT_NAME\", sizeof(\"SCRIPT_NAME\"), (void**)&z_script_name) || IS_STRING != Z_TYPE_PP(z_script_name) || !strstr(Z_STRVAL_PP(z_script_name), basename)) { return; } if (SUCCESS == zend_hash_find(_server, \"PATH_INFO\", sizeof(\"PATH_INFO\"), (void**)&z_path_info) && IS_STRING == Z_TYPE_PP(z_path_info)) { entry_len = Z_STRLEN_PP(z_path_info); entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len); path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1); memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1); free_pathinfo = 1; } else { entry_len = 0; entry = estrndup(\"\", 0); path_info = Z_STRVAL_PP(z_script_name); } pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); } else { char *testit; testit = sapi_getenv(\"SCRIPT_NAME\", sizeof(\"SCRIPT_NAME\")-1 TSRMLS_CC); if (!(pt = strstr(testit, basename))) { efree(testit); return; } path_info = sapi_getenv(\"PATH_INFO\", sizeof(\"PATH_INFO\")-1 TSRMLS_CC); if (path_info) { entry = path_info; entry_len = strlen(entry); spprintf(&path_info, 0, \"%s%s\", testit, path_info); free_pathinfo = 1; } else { path_info = testit; free_pathinfo = 1; entry = estrndup(\"\", 0); entry_len = 0; } pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname))); } not_cgi = 0; } else { path_info = SG(request_info).request_uri; if (!(pt = strstr(path_info, basename))) { \/* this can happen with rewrite rules - and we have no idea what to do then, so return *\/ return; } entry_len = strlen(path_info); entry_len -= (pt - path_info) + (fname_len - (basename - fname)); entry = estrndup(pt + (fname_len - (basename - fname)), entry_len); pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname))); not_cgi = 1; } if (rewrite) { zend_fcall_info fci; zend_fcall_info_cache fcc; zval *params, *retval_ptr, **zp[1]; MAKE_STD_ZVAL(params); ZVAL_STRINGL(params, entry, entry_len, 1); zp[0] = ¶ms; #if PHP_VERSION_ID < 50300 if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) { #else if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) { #endif zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar error: invalid rewrite callback\"); if (free_pathinfo) { efree(path_info); } return; } fci.param_count = 1; fci.params = zp; #if PHP_VERSION_ID < 50300 ++(params->refcount); #else Z_ADDREF_P(params); #endif fci.retval_ptr_ptr = &retval_ptr; if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) { if (!EG(exception)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar error: failed to call rewrite callback\"); } if (free_pathinfo) { efree(path_info); } return; } if (!fci.retval_ptr_ptr || !retval_ptr) { if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar error: rewrite callback must return a string or false\"); return; } switch (Z_TYPE_P(retval_ptr)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(retval_ptr TSRMLS_CC); \/* break intentionally omitted *\/ #endif case IS_STRING: efree(entry); if (fci.retval_ptr_ptr != &retval_ptr) { entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr)); entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr); } else { entry = Z_STRVAL_P(retval_ptr); entry_len = Z_STRLEN_P(retval_ptr); } break; case IS_BOOL: phar_do_403(entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); return; default: efree(retval_ptr); if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar error: rewrite callback must return a string or false\"); return; } } if (entry_len) { phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC); } if (!entry_len || (entry_len == 1 && entry[0] == '\/')) { efree(entry); \/* direct request *\/ if (index_php_len) { entry = index_php; entry_len = index_php_len; if (entry[0] != '\/') { spprintf(&entry, 0, \"\/%s\", index_php); ++entry_len; } } else { \/* assume \"index.php\" is starting point *\/ entry = estrndup(\"\/index.php\", sizeof(\"\/index.php\")); entry_len = sizeof(\"\/index.php\")-1; } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); } else { char *tmp = NULL, sa = '\\0'; sapi_header_line ctr = {0}; ctr.response_code = 301; ctr.line_len = sizeof(\"HTTP\/1.1 301 Moved Permanently\")-1; ctr.line = \"HTTP\/1.1 301 Moved Permanently\"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); if (not_cgi) { tmp = strstr(path_info, basename) + fname_len; sa = *tmp; *tmp = '\\0'; } ctr.response_code = 0; if (path_info[strlen(path_info)-1] == '\/') { ctr.line_len = spprintf(&(ctr.line), 4096, \"Location: %s%s\", path_info, entry + 1); } else { ctr.line_len = spprintf(&(ctr.line), 4096, \"Location: %s%s\", path_info, entry); } if (not_cgi) { *tmp = sa; } if (free_pathinfo) { efree(path_info); } sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); sapi_send_headers(TSRMLS_C); efree(ctr.line); zend_bailout(); } } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); #ifdef PHP_WIN32 efree(fname); #endif zend_bailout(); } if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) { const char *ext = zend_memrchr(entry, '.', entry_len); zval **val; if (ext) { ++ext; if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) { switch (Z_TYPE_PP(val)) { case IS_LONG: if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) { mime_type = \"\"; code = Z_LVAL_PP(val); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed\"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } break; case IS_STRING: mime_type = Z_STRVAL_PP(val); code = PHAR_MIME_OTHER; break; default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed\"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } } } } if (!mime_type) { code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC); } ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC); } \/* }}} *\/ \/* {{{ proto void Phar::mungServer(array munglist) * Defines a list of up to 4 $_SERVER variables that should be modified for execution * to mask the presence of the phar archive. This should be used in conjunction with * Phar::webPhar(), and has no effect otherwise * SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME *\/ PHP_METHOD(Phar, mungServer) { zval *mungvalues; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"a\", &mungvalues) == FAILURE) { return; } if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME\"); return; } if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME\"); return; } phar_request_initialize(TSRMLS_C); for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) { zval **data = NULL; if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"unable to retrieve array value in Phar::mungServer()\"); return; } if (Z_TYPE_PP(data) != IS_STRING) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME\"); return; } if (Z_STRLEN_PP(data) == sizeof(\"PHP_SELF\")-1 && !strncmp(Z_STRVAL_PP(data), \"PHP_SELF\", sizeof(\"PHP_SELF\")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF; } if (Z_STRLEN_PP(data) == sizeof(\"REQUEST_URI\")-1) { if (!strncmp(Z_STRVAL_PP(data), \"REQUEST_URI\", sizeof(\"REQUEST_URI\")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI; } if (!strncmp(Z_STRVAL_PP(data), \"SCRIPT_NAME\", sizeof(\"SCRIPT_NAME\")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME; } } if (Z_STRLEN_PP(data) == sizeof(\"SCRIPT_FILENAME\")-1 && !strncmp(Z_STRVAL_PP(data), \"SCRIPT_FILENAME\", sizeof(\"SCRIPT_FILENAME\")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME; } } } \/* }}} *\/ \/* {{{ proto void Phar::interceptFileFuncs() * instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions * and return stat on files within the phar for relative paths * * Once called, this cannot be reversed, and continue until the end of the request. * * This allows legacy scripts to be pharred unmodified *\/ PHP_METHOD(Phar, interceptFileFuncs) { if (zend_parse_parameters_none() == FAILURE) { return; } phar_intercept_functions(TSRMLS_C); } \/* }}} *\/ \/* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]]) * Return a stub that can be used to run a phar-based archive without the phar extension * indexfile is the CLI startup filename, which defaults to \"index.php\", webindexfile * is the web startup filename, and also defaults to \"index.php\" *\/ PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *stub, *error; int index_len = 0, webindex_len = 0; size_t stub_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|ss\", &index, &index_len, &webindex, &webindex_len) == FAILURE) { return; } stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); return; } RETURN_STRINGL(stub, stub_len, 0); } \/* }}} *\/ \/* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]]) * Reads the currently executed file (a phar) and registers its manifest *\/ PHP_METHOD(Phar, mapPhar) { char *alias = NULL, *error; int alias_len = 0; long dataoffset = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s!l\", &alias, &alias_len, &dataoffset) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } } \/* }}} *\/ \/* {{{ proto mixed Phar::loadPhar(string filename [, string alias]) * Loads any phar archive with an alias *\/ PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; int fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|s!\", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } } \/* }}} *\/ \/* {{{ proto string Phar::apiVersion() * Returns the api version *\/ PHP_METHOD(Phar, apiVersion) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1); } \/* }}}*\/ \/* {{{ proto bool Phar::canCompress([int method]) * Returns whether phar extension supports compression using zlib\/bzip2 *\/ PHP_METHOD(Phar, canCompress) { long method = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|l\", &method) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (PHAR_G(has_zlib)) { RETURN_TRUE; } else { RETURN_FALSE; } case PHAR_ENT_COMPRESSED_BZ2: if (PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } default: if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } } } \/* }}} *\/ \/* {{{ proto bool Phar::canWrite() * Returns whether phar extension supports writing and creating phars *\/ PHP_METHOD(Phar, canWrite) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(!PHAR_G(readonly)); } \/* }}} *\/ \/* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true]) * Returns whether the given filename is a valid phar filename *\/ PHP_METHOD(Phar, isValidPharFilename) { char *fname; const char *ext_str; int fname_len, ext_len, is_executable; zend_bool executable = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|b\", &fname, &fname_len, &executable) == FAILURE) { return; } is_executable = executable; RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS); } \/* }}} *\/ #if HAVE_SPL \/** * from spl_directory *\/ static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) \/* {{{ *\/ { phar_archive_data *phar = (phar_archive_data *) object->oth; if (!phar->is_persistent) { phar_archive_delref(phar TSRMLS_CC); } object->oth = NULL; } \/* }}} *\/ \/** * from spl_directory *\/ static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) \/* {{{ *\/ { phar_archive_data *phar_data = (phar_archive_data *) dst->oth; if (!phar_data->is_persistent) { ++(phar_data->refcount); } } \/* }}} *\/ static spl_other_handler phar_spl_foreign_handler = { phar_spl_foreign_dtor, phar_spl_foreign_clone }; #endif \/* HAVE_SPL *\/ \/* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]]) * Construct a Phar archive object * * proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR]) * Construct a PharData archive object * * This function is used as the constructor for both the Phar and PharData * classes, hence the two prototypes above. *\/ PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, \"Cannot instantiate Phar object without SPL extension\"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|ls!l\", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|ls!\", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Cannot call constructor twice\"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { \/* use arch (the basename for the archive) for fname instead of fname *\/ \/* this allows support for RecursiveDirectoryIterator of subdirectories *\/ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"%s\", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Phar creation or opening failed\"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"PharData class can only be used for non-executable tar and zip archives\"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Phar class can only be used for executable tar and zip archives\"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, \"phar:\/\/%s%s\", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, \"phar:\/\/%s\", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, \"__construct\", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { \/* register this guy so we can modify if necessary *\/ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif \/* HAVE_SPL *\/ } \/* }}} *\/ \/* {{{ proto array Phar::getSupportedSignatures() * Return array of supported signature types *\/ PHP_METHOD(Phar, getSupportedSignatures) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); add_next_index_stringl(return_value, \"MD5\", 3, 1); add_next_index_stringl(return_value, \"SHA-1\", 5, 1); #ifdef PHAR_HASH_OK add_next_index_stringl(return_value, \"SHA-256\", 7, 1); add_next_index_stringl(return_value, \"SHA-512\", 7, 1); #endif #if PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, \"OpenSSL\", 7, 1); #else if (zend_hash_exists(&module_registry, \"openssl\", sizeof(\"openssl\"))) { add_next_index_stringl(return_value, \"OpenSSL\", 7, 1); } #endif } \/* }}} *\/ \/* {{{ proto array Phar::getSupportedCompression() * Return array of supported comparession algorithms *\/ PHP_METHOD(Phar, getSupportedCompression) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); phar_request_initialize(TSRMLS_C); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, \"GZ\", 2, 1); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, \"BZIP2\", 5, 1); } } \/* }}} *\/ \/* {{{ proto array Phar::unlinkArchive(string archive) * Completely remove a phar archive from memory and disk *\/ PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; int fname_len, zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown phar archive \\\"\\\"\"); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown phar archive \\\"%s\\\": %s\", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown phar archive \\\"%s\\\"\", fname); } return; } zname = (char*)zend_get_executed_filename(TSRMLS_C); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, \"phar:\/\/\", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar archive \\\"%s\\\" cannot be unlinked from within itself\", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar archive \\\"%s\\\" is in phar.cache_list, cannot unlinkArchive()\", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar archive \\\"%s\\\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()\", fname); return; } fname = estrndup(phar->fname, phar->fname_len); \/* invalidate phar cache *\/ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar TSRMLS_CC); unlink(fname); efree(fname); RETURN_TRUE; } \/* }}} *\/ #if HAVE_SPL #define PHAR_ARCHIVE_OBJECT() \\ phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \\ if (!phar_obj->arc.archive) { \\ zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \\ \"Cannot call method on an uninitialized Phar object\"); \\ return; \\ } \/* {{{ proto void Phar::__destruct() * if persistent, remove from the cache *\/ PHP_METHOD(Phar, __destruct) { phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) { zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive)); } } \/* }}} *\/ struct _phar_t { phar_archive_object *p; zend_class_entry *c; char *b; uint l; zval *ret; int count; php_stream *fp; }; static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) \/* {{{ *\/ { zval **value; zend_uchar key_type; zend_bool close_fp = 1; ulong int_key; struct _phar_t *p_obj = (struct _phar_t*) puser; uint str_key_len, base_len = p_obj->l, fname_len; phar_entry_data *data; php_stream *fp; size_t contents_len; char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL; phar_zstr key; char *str_key; zend_class_entry *ce = p_obj->c; phar_archive_object *phar_obj = p_obj->p; char *str = \"[stream]\"; iter->funcs->get_current_data(iter, &value TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (!value) { \/* failure in get_current_data *\/ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned no value\", ce->name); return ZEND_HASH_APPLY_STOP; } switch (Z_TYPE_PP(value)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(*(value) TSRMLS_CC); \/* break intentionally omitted *\/ #endif case IS_STRING: break; case IS_RESOURCE: php_stream_from_zval_no_verify(fp, value); if (!fp) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Iterator %v returned an invalid stream handle\", ce->name); return ZEND_HASH_APPLY_STOP; } if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid key (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { \/* IS_UNICODE == 10 *\/ #if PHP_VERSION_ID < 60000 \/* this can never happen, but fixes a compile warning *\/ spprintf(&str_key, 0, \"%s\", key); #else spprintf(&str_key, 0, \"%v\", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\\0') { str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid key (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } close_fp = 0; opened = (char *) estrndup(str, sizeof(\"[stream]\") - 1); goto after_open_fp; case IS_OBJECT: if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) { char *test = NULL; zval dummy; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC); if (!base_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Iterator %v returns an SplFileInfo object, so base directory must be specified\", ce->name); return ZEND_HASH_APPLY_STOP; } switch (intern->type) { case SPL_FS_DIR: #if PHP_VERSION_ID >= 60000 test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s; #elif PHP_VERSION_ID >= 50300 test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC); #else test = intern->path; #endif fname_len = spprintf(&fname, 0, \"%s%c%s\", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC); if (Z_BVAL(dummy)) { \/* ignore directories *\/ efree(fname); return ZEND_HASH_APPLY_KEEP; } test = expand_filepath(fname, NULL TSRMLS_CC); efree(fname); if (test) { fname = test; fname_len = strlen(fname); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Could not resolve file path\"); return ZEND_HASH_APPLY_STOP; } save = fname; goto phar_spl_fileinfo; case SPL_FS_INFO: case SPL_FS_FILE: #if PHP_VERSION_ID >= 60000 if (intern->file_name_type == IS_UNICODE) { zval zv; INIT_ZVAL(zv); Z_UNIVAL(zv) = intern->file_name; Z_UNILEN(zv) = intern->file_name_len; Z_TYPE(zv) = IS_UNICODE; zval_copy_ctor(&zv); zval_unicode_to_string(&zv TSRMLS_CC); fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC); ezfree(Z_UNIVAL(zv)); } else { fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC); } #else fname = expand_filepath(intern->file_name, NULL TSRMLS_CC); #endif if (!fname) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Could not resolve file path\"); return ZEND_HASH_APPLY_STOP; } fname_len = strlen(fname); save = fname; goto phar_spl_fileinfo; } } \/* fall-through *\/ default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid value (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } fname = Z_STRVAL_PP(value); fname_len = Z_STRLEN_PP(value); phar_spl_fileinfo: if (base_len) { temp = expand_filepath(base, NULL TSRMLS_CC); if (!temp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Could not resolve file path\"); if (save) { efree(save); } return ZEND_HASH_APPLY_STOP; } base = temp; base_len = strlen(base); if (strstr(fname, base)) { str_key_len = fname_len - base_len; if (str_key_len <= 0) { if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_KEEP; } str_key = fname + base_len; if (*str_key == '\/' || *str_key == '\\\\') { str_key++; str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned a path \\\"%s\\\" that is not in the base directory \\\"%s\\\"\", ce->name, fname, base); if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_STOP; } } else { if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid key (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { \/* IS_UNICODE == 10 *\/ #if PHP_VERSION_ID < 60000 \/* this can never happen, but fixes a compile warning *\/ spprintf(&str_key, 0, \"%s\", key); #else spprintf(&str_key, 0, \"%v\", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\\0') str_key_len--; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid key (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned a path \\\"%s\\\" that safe mode prevents opening\", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned a path \\\"%s\\\" that open_basedir prevents opening\", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } \/* try to open source file, then create internal phar file and copy contents *\/ fp = php_stream_open_wrapper(fname, \"rb\", STREAM_MUST_SEEK|0, &opened); if (!fp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned a file that could not be opened \\\"%s\\\"\", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } after_open_fp: if (str_key_len >= sizeof(\".phar\")-1 && !memcmp(str_key, \".phar\", sizeof(\".phar\")-1)) { \/* silently skip any files that would be added to the magic .phar directory *\/ if (save) { efree(save); } if (temp) { efree(temp); } if (opened) { efree(opened); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_KEEP; } if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, \"w+b\", 0, &error, 1 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Entry %s cannot be created: %s\", str_key, error); efree(error); if (save) { efree(save); } if (opened) { efree(opened); } if (temp) { efree(temp); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_STOP; } else { if (error) { efree(error); } \/* convert to PHAR_UFP *\/ if (data->internal_file->fp_type == PHAR_MOD) { php_stream_close(data->internal_file->fp); } data->internal_file->fp = NULL; data->internal_file->fp_type = PHAR_UFP; data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); data->fp = NULL; phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = php_stream_tell(p_obj->fp) - data->internal_file->offset; } if (close_fp) { php_stream_close(fp); } add_assoc_string(p_obj->ret, str_key, opened, 0); if (save) { efree(save); } if (temp) { efree(temp); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; phar_entry_delref(data TSRMLS_CC); return ZEND_HASH_APPLY_KEEP; } \/* }}} *\/ \/* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex]) * Construct a phar archive from an existing directory, recursively. * Optional second parameter is a regular expression for filtering directory contents. * * Return value is an array mapping phar index to actual files added. *\/ PHP_METHOD(Phar, buildFromDirectory) { char *dir, *error, *regex = NULL; int dir_len, regex_len = 0; zend_bool apply_reg = 0; zval arg, arg2, *iter, *iteriter, *regexiter = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot write to archive - write operations restricted by INI setting\"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|s\", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) { RETURN_FALSE; } MAKE_STD_ZVAL(iter); if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) { zval_ptr_dtor(&iter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate directory iterator for %s\", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg); ZVAL_STRINGL(&arg, dir, dir_len, 0); INIT_PZVAL(&arg2); #if PHP_VERSION_ID < 50300 ZVAL_LONG(&arg2, 0); #else ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS); #endif zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator, &spl_ce_RecursiveDirectoryIterator->constructor, \"__construct\", NULL, &arg, &arg2); if (EG(exception)) { zval_ptr_dtor(&iter); RETURN_FALSE; } MAKE_STD_ZVAL(iteriter); if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate directory iterator for %s\", phar_obj->arc.archive->fname); RETURN_FALSE; } zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator, &spl_ce_RecursiveIteratorIterator->constructor, \"__construct\", NULL, iter); if (EG(exception)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); RETURN_FALSE; } zval_ptr_dtor(&iter); if (regex_len > 0) { apply_reg = 1; MAKE_STD_ZVAL(regexiter); if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) { zval_ptr_dtor(&iteriter); zval_dtor(regexiter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate regex iterator for %s\", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg2); ZVAL_STRINGL(&arg2, regex, regex_len, 0); zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator, &spl_ce_RegexIterator->constructor, \"__construct\", NULL, iteriter, &arg2); } array_init(return_value); pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter); pass.p = phar_obj; pass.b = dir; pass.l = dir_len; pass.count = 0; pass.ret = return_value; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar \\\"%s\\\" unable to create temporary file\", phar_obj->arc.archive->fname); return; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(®exiter); } php_stream_close(pass.fp); zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar \\\"%s\\\" is persistent, unable to copy on write\", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(®exiter); } phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } } else { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(®exiter); } php_stream_close(pass.fp); } } \/* }}} *\/ \/* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory]) * Construct a phar archive from an iterator. The iterator must return a series of strings * that are full paths to files that should be added to the phar. The iterator key should * be the path that the file will have within the phar archive. * * If base directory is specified, then the key will be ignored, and instead the portion of * the current value minus the base directory will be used * * Returned is an array mapping phar index to actual file added *\/ PHP_METHOD(Phar, buildFromIterator) { zval *obj; char *error; uint base_len = 0; char *base = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot write out phar archive, phar is read-only\"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"O|s\", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar \\\"%s\\\" is persistent, unable to copy on write\", phar_obj->arc.archive->fname); return; } array_init(return_value); pass.c = Z_OBJCE_P(obj); pass.p = phar_obj; pass.b = base; pass.l = base_len; pass.ret = return_value; pass.count = 0; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar \\\"%s\\\": unable to create temporary file\", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } } else { php_stream_close(pass.fp); } } \/* }}} *\/ \/* {{{ proto int Phar::count() * Returns the number of entries in the Phar archive *\/ PHP_METHOD(Phar, count) { PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest)); } \/* }}} *\/ \/* {{{ proto bool Phar::isFileFormat(int format) * Returns true if the phar archive is based on the tar\/zip\/phar file format depending * on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in *\/ PHP_METHOD(Phar, isFileFormat) { long type; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &type) == FAILURE) { RETURN_FALSE; } switch (type) { case PHAR_FORMAT_TAR: RETURN_BOOL(phar_obj->arc.archive->is_tar); case PHAR_FORMAT_ZIP: RETURN_BOOL(phar_obj->arc.archive->is_zip); case PHAR_FORMAT_PHAR: RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip); default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown file format specified\"); } } \/* }}} *\/ static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) \/* {{{ *\/ { char *error; off_t offset; phar_entry_info *link; if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) { if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot convert phar archive \\\"%s\\\", unable to open entry \\\"%s\\\" contents: %s\", entry->phar->fname, entry->filename, error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot convert phar archive \\\"%s\\\", unable to open entry \\\"%s\\\" contents\", entry->phar->fname, entry->filename); } return FAILURE; } \/* copy old contents in entirety *\/ phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC); offset = php_stream_tell(fp); link = phar_get_link_source(entry TSRMLS_CC); if (!link) { link = entry; } if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot convert phar archive \\\"%s\\\", unable to copy entry \\\"%s\\\" contents\", entry->phar->fname, entry->filename); return FAILURE; } if (entry->fp_type == PHAR_MOD) { \/* save for potential restore on error *\/ entry->cfp = entry->fp; entry->fp = NULL; } \/* set new location of file contents *\/ entry->fp_type = PHAR_FP; entry->offset = offset; return SUCCESS; } \/* }}} *\/ static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) \/* {{{ *\/ { const char *oldname = NULL; char *oldpath = NULL; char *basename = NULL, *basepath = NULL; char *newname = NULL, *newpath = NULL; zval *ret, arg1; zend_class_entry *ce; char *error; const char *pcr_error; int ext_len = ext ? strlen(ext) : 0; int oldname_len; phar_archive_data **pphar = NULL; php_stream_statbuf ssb; if (!ext) { if (phar->is_zip) { if (phar->is_data) { ext = \"zip\"; } else { ext = \"phar.zip\"; } } else if (phar->is_tar) { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: if (phar->is_data) { ext = \"tar.gz\"; } else { ext = \"phar.tar.gz\"; } break; case PHAR_FILE_COMPRESSED_BZ2: if (phar->is_data) { ext = \"tar.bz2\"; } else { ext = \"phar.tar.bz2\"; } break; default: if (phar->is_data) { ext = \"tar\"; } else { ext = \"phar.tar\"; } } } else { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: ext = \"phar.gz\"; break; case PHAR_FILE_COMPRESSED_BZ2: ext = \"phar.bz2\"; break; default: ext = \"phar\"; } } } else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) { if (phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext); } return NULL; } if (ext[0] == '.') { ++ext; } oldpath = estrndup(phar->fname, phar->fname_len); oldname = zend_memrchr(phar->fname, '\/', phar->fname_len); ++oldname; oldname_len = strlen(oldname); basename = estrndup(oldname, oldname_len); spprintf(&newname, 0, \"%s.%s\", strtok(basename, \".\"), ext); efree(basename); basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len)); phar->fname_len = spprintf(&newpath, 0, \"%s%s\", basepath, newname); phar->fname = newpath; phar->ext = newpath + phar->fname_len - strlen(ext) - 1; efree(basepath); efree(newname); if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, new phar name is in phar.cache_list\", phar->fname); return NULL; } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) { if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) { if (!zend_hash_num_elements(&phar->manifest)) { (*pphar)->is_tar = phar->is_tar; (*pphar)->is_zip = phar->is_zip; (*pphar)->is_data = phar->is_data; (*pphar)->flags = phar->flags; (*pphar)->fp = phar->fp; phar->fp = NULL; phar_destroy_phar_data(phar TSRMLS_CC); phar = *pphar; phar->refcount++; newpath = oldpath; goto its_ok; } } efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, a phar with that name already exists\", phar->fname); return NULL; } its_ok: if (SUCCESS == php_stream_stat_path(newpath, &ssb)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" exists and must be unlinked prior to conversion\", newpath); efree(oldpath); return NULL; } if (!phar->is_data) { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext); return NULL; } if (phar->alias) { if (phar->is_temporary_alias) { phar->alias = NULL; phar->alias_len = 0; } else { phar->alias = estrndup(newpath, strlen(newpath)); phar->alias_len = strlen(newpath); phar->is_temporary_alias = 1; zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL); } } } else { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext); return NULL; } phar->alias = NULL; phar->alias_len = 0; } if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars\", phar->fname); return NULL; } phar_flush(phar, 0, 0, 1, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"%s\", error); efree(error); efree(oldpath); return NULL; } efree(oldpath); if (phar->is_data) { ce = phar_ce_data; } else { ce = phar_ce_archive; } MAKE_STD_ZVAL(ret); if (SUCCESS != object_init_ex(ret, ce)) { zval_dtor(ret); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate phar object when converting archive \\\"%s\\\"\", phar->fname); return NULL; } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0); zend_call_method_with_1_params(&ret, ce, &ce->constructor, \"__construct\", NULL, &arg1); return ret; } \/* }}} *\/ static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) \/* {{{ *\/ { phar_archive_data *phar; phar_entry_info *entry, newentry; zval *ret; \/* invalidate phar cache *\/ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data)); \/* set whole-archive compression and type from parameter *\/ phar->flags = flags; phar->is_data = source->is_data; switch (convert) { case PHAR_FORMAT_TAR: phar->is_tar = 1; break; case PHAR_FORMAT_ZIP: phar->is_zip = 1; break; default: phar->is_data = 0; break; } zend_hash_init(&(phar->manifest), sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&phar->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&phar->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); phar->fp = php_stream_fopen_tmpfile(); if (phar->fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"unable to create temporary file\"); return NULL; } phar->fname = source->fname; phar->fname_len = source->fname_len; phar->is_temporary_alias = source->is_temporary_alias; phar->alias = source->alias; if (source->metadata) { zval *t; t = source->metadata; ALLOC_ZVAL(phar->metadata); *phar->metadata = *t; zval_copy_ctor(phar->metadata); #if PHP_VERSION_ID < 50300 phar->metadata->refcount = 1; #else Z_SET_REFCOUNT_P(phar->metadata, 1); #endif phar->metadata_len = 0; } \/* first copy each file's uncompressed contents to a temporary file and set per-file flags *\/ for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) { if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot convert phar archive \\\"%s\\\"\", source->fname); return NULL; } newentry = *entry; if (newentry.link) { newentry.link = estrdup(newentry.link); goto no_copy; } if (newentry.tmp) { newentry.tmp = estrdup(newentry.tmp); goto no_copy; } newentry.metadata_str.c = 0; if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); \/* exception already thrown *\/ return NULL; } no_copy: newentry.filename = estrndup(newentry.filename, newentry.filename_len); if (newentry.metadata) { zval *t; t = newentry.metadata; ALLOC_ZVAL(newentry.metadata); *newentry.metadata = *t; zval_copy_ctor(newentry.metadata); #if PHP_VERSION_ID < 50300 newentry.metadata->refcount = 1; #else Z_SET_REFCOUNT_P(newentry.metadata, 1); #endif newentry.metadata_str.c = NULL; newentry.metadata_str.len = 0; } newentry.is_zip = phar->is_zip; newentry.is_tar = phar->is_tar; if (newentry.is_tar) { newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE); } newentry.is_modified = 1; newentry.phar = phar; newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; \/* remove compression from old_flags *\/ phar_set_inode(&newentry TSRMLS_CC); zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL); phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC); } if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) { return ret; } else { zend_hash_destroy(&(phar->manifest)); zend_hash_destroy(&(phar->mounted_dirs)); zend_hash_destroy(&(phar->virtual_dirs)); php_stream_close(phar->fp); efree(phar->fname); efree(phar); return NULL; \/* }}} *\/","output":{"is_vulnerable":"True","vulnerability_types":["Improper Input Validation"],"explanation":"The phar_convert_to_other function in ext\/phar\/phar_object.c in PHP before 5.4.43, 5.5.x before 5.5.27, and 5.6.x before 5.6.11 does not validate a file pointer before a close operation, which allows remote attackers to cause a denial of service (segmentation fault) or possibly have unspecified other impact via a crafted TAR archive that is mishandled in a Phar::convertToData call.","severity_level":"High","cwe":"CWE-20","cve":"CVE-2015-5589"}} -{"idx":313408,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MaxTextExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False when converting or mogrifying *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; \/* Skip nominal layer count, frame count, and play time *\/ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\", \"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, \"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); mng_info=MngInfoFreeStruct(mng_info); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (((p-chunk) < (long) length) && *p) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters \", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(png_uint_32) p[12] << 8) & png_uint_32) p[13]; else basi_red=0; if (length > 15) basi_green=(png_uint_32) p[14] << 8) & png_uint_32) p[15]; else basi_green=0; if (length > 17) basi_blue=(png_uint_32) p[16] << 8) & png_uint_32) p[17]; else basi_blue=0; if (length > 19) basi_alpha=(png_uint_32) p[18] << 8) & png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { if (prev != (PixelPacket *) NULL) prev=(PixelPacket *) RelinquishMagickMemory(prev); if (next != (PixelPacket *) NULL) next=(PixelPacket *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (PixelPacket *) NULL) break; q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { \/* Interpolate *\/ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))\/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ else { \/* Interpolate *\/ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":474677,"input":"NumberFormatTest::TestParseCurrencyInUCurr() { const char* DATA[] = { \"1.00 US DOLLAR\", \/\/ case in-sensitive \"$1.00\", \"USD1.00\", \"usd1.00\", \/\/ case in-sensitive: #13696 \"US dollar1.00\", \"US dollars1.00\", \"$1.00\", \"A$1.00\", \"ADP1.00\", \"ADP1.00\", \"AED1.00\", \"AED1.00\", \"AFA1.00\", \"AFA1.00\", \"AFN1.00\", \"ALL1.00\", \"AMD1.00\", \"ANG1.00\", \"AOA1.00\", \"AOK1.00\", \"AOK1.00\", \"AON1.00\", \"AON1.00\", \"AOR1.00\", \"AOR1.00\", \"ARS1.00\", \"ARA1.00\", \"ARA1.00\", \"ARP1.00\", \"ARP1.00\", \"ARS1.00\", \"ATS1.00\", \"ATS1.00\", \"AUD1.00\", \"AWG1.00\", \"AZM1.00\", \"AZM1.00\", \"AZN1.00\", \"Afghan Afghani (1927\\\\u20132002)1.00\", \"Afghan afghani (1927\\\\u20132002)1.00\", \"Afghan Afghani1.00\", \"Afghan Afghanis1.00\", \"Albanian Lek1.00\", \"Albanian lek1.00\", \"Albanian lek\\\\u00eb1.00\", \"Algerian Dinar1.00\", \"Algerian dinar1.00\", \"Algerian dinars1.00\", \"Andorran Peseta1.00\", \"Andorran peseta1.00\", \"Andorran pesetas1.00\", \"Angolan Kwanza (1977\\\\u20131991)1.00\", \"Angolan Readjusted Kwanza (1995\\\\u20131999)1.00\", \"Angolan Kwanza1.00\", \"Angolan New Kwanza (1990\\\\u20132000)1.00\", \"Angolan kwanza (1977\\\\u20131991)1.00\", \"Angolan readjusted kwanza (1995\\\\u20131999)1.00\", \"Angolan kwanza1.00\", \"Angolan kwanzas (1977\\\\u20131991)1.00\", \"Angolan readjusted kwanzas (1995\\\\u20131999)1.00\", \"Angolan kwanzas1.00\", \"Angolan new kwanza (1990\\\\u20132000)1.00\", \"Angolan new kwanzas (1990\\\\u20132000)1.00\", \"Argentine Austral1.00\", \"Argentine Peso (1983\\\\u20131985)1.00\", \"Argentine Peso1.00\", \"Argentine austral1.00\", \"Argentine australs1.00\", \"Argentine peso (1983\\\\u20131985)1.00\", \"Argentine peso1.00\", \"Argentine pesos (1983\\\\u20131985)1.00\", \"Argentine pesos1.00\", \"Armenian Dram1.00\", \"Armenian dram1.00\", \"Armenian drams1.00\", \"Aruban Florin1.00\", \"Aruban florin1.00\", \"Australian Dollar1.00\", \"Australian dollar1.00\", \"Australian dollars1.00\", \"Austrian Schilling1.00\", \"Austrian schilling1.00\", \"Austrian schillings1.00\", \"Azerbaijani Manat (1993\\\\u20132006)1.00\", \"Azerbaijani Manat1.00\", \"Azerbaijani manat (1993\\\\u20132006)1.00\", \"Azerbaijani manat1.00\", \"Azerbaijani manats (1993\\\\u20132006)1.00\", \"Azerbaijani manats1.00\", \"BAD1.00\", \"BAD1.00\", \"BAM1.00\", \"BBD1.00\", \"BDT1.00\", \"BEC1.00\", \"BEC1.00\", \"BEF1.00\", \"BEL1.00\", \"BEL1.00\", \"BGL1.00\", \"BGN1.00\", \"BGN1.00\", \"BHD1.00\", \"BIF1.00\", \"BMD1.00\", \"BND1.00\", \"BOB1.00\", \"BOP1.00\", \"BOP1.00\", \"BOV1.00\", \"BOV1.00\", \"BRB1.00\", \"BRB1.00\", \"BRC1.00\", \"BRC1.00\", \"BRE1.00\", \"BRE1.00\", \"BRL1.00\", \"BRN1.00\", \"BRN1.00\", \"BRR1.00\", \"BRR1.00\", \"BSD1.00\", \"BSD1.00\", \"BTN1.00\", \"BUK1.00\", \"BUK1.00\", \"BWP1.00\", \"BYB1.00\", \"BYB1.00\", \"BYR1.00\", \"BZD1.00\", \"Bahamian Dollar1.00\", \"Bahamian dollar1.00\", \"Bahamian dollars1.00\", \"Bahraini Dinar1.00\", \"Bahraini dinar1.00\", \"Bahraini dinars1.00\", \"Bangladeshi Taka1.00\", \"Bangladeshi taka1.00\", \"Bangladeshi takas1.00\", \"Barbadian Dollar1.00\", \"Barbadian dollar1.00\", \"Barbadian dollars1.00\", \"Belarusian Ruble (1994\\\\u20131999)1.00\", \"Belarusian Ruble1.00\", \"Belarusian ruble (1994\\\\u20131999)1.00\", \"Belarusian rubles (1994\\\\u20131999)1.00\", \"Belarusian ruble1.00\", \"Belarusian rubles1.00\", \"Belgian Franc (convertible)1.00\", \"Belgian Franc (financial)1.00\", \"Belgian Franc1.00\", \"Belgian franc (convertible)1.00\", \"Belgian franc (financial)1.00\", \"Belgian franc1.00\", \"Belgian francs (convertible)1.00\", \"Belgian francs (financial)1.00\", \"Belgian francs1.00\", \"Belize Dollar1.00\", \"Belize dollar1.00\", \"Belize dollars1.00\", \"Bermudan Dollar1.00\", \"Bermudan dollar1.00\", \"Bermudan dollars1.00\", \"Bhutanese Ngultrum1.00\", \"Bhutanese ngultrum1.00\", \"Bhutanese ngultrums1.00\", \"Bolivian Mvdol1.00\", \"Bolivian Peso1.00\", \"Bolivian mvdol1.00\", \"Bolivian mvdols1.00\", \"Bolivian peso1.00\", \"Bolivian pesos1.00\", \"Bolivian Boliviano1.00\", \"Bolivian Boliviano1.00\", \"Bolivian Bolivianos1.00\", \"Bosnia-Herzegovina Convertible Mark1.00\", \"Bosnia-Herzegovina Dinar (1992\\\\u20131994)1.00\", \"Bosnia-Herzegovina convertible mark1.00\", \"Bosnia-Herzegovina convertible marks1.00\", \"Bosnia-Herzegovina dinar (1992\\\\u20131994)1.00\", \"Bosnia-Herzegovina dinars (1992\\\\u20131994)1.00\", \"Botswanan Pula1.00\", \"Botswanan pula1.00\", \"Botswanan pulas1.00\", \"Brazilian New Cruzado (1989\\\\u20131990)1.00\", \"Brazilian Cruzado (1986\\\\u20131989)1.00\", \"Brazilian Cruzeiro (1990\\\\u20131993)1.00\", \"Brazilian New Cruzeiro (1967\\\\u20131986)1.00\", \"Brazilian Cruzeiro (1993\\\\u20131994)1.00\", \"Brazilian Real1.00\", \"Brazilian new cruzado (1989\\\\u20131990)1.00\", \"Brazilian new cruzados (1989\\\\u20131990)1.00\", \"Brazilian cruzado (1986\\\\u20131989)1.00\", \"Brazilian cruzados (1986\\\\u20131989)1.00\", \"Brazilian cruzeiro (1990\\\\u20131993)1.00\", \"Brazilian new cruzeiro (1967\\\\u20131986)1.00\", \"Brazilian cruzeiro (1993\\\\u20131994)1.00\", \"Brazilian cruzeiros (1990\\\\u20131993)1.00\", \"Brazilian new cruzeiros (1967\\\\u20131986)1.00\", \"Brazilian cruzeiros (1993\\\\u20131994)1.00\", \"Brazilian real1.00\", \"Brazilian reals1.00\", \"British Pound1.00\", \"British pound1.00\", \"British pounds1.00\", \"Brunei Dollar1.00\", \"Brunei dollar1.00\", \"Brunei dollars1.00\", \"Bulgarian Hard Lev1.00\", \"Bulgarian Lev1.00\", \"Bulgarian Leva1.00\", \"Bulgarian hard lev1.00\", \"Bulgarian hard leva1.00\", \"Bulgarian lev1.00\", \"Burmese Kyat1.00\", \"Burmese kyat1.00\", \"Burmese kyats1.00\", \"Burundian Franc1.00\", \"Burundian franc1.00\", \"Burundian francs1.00\", \"CA$1.00\", \"CAD1.00\", \"CDF1.00\", \"CDF1.00\", \"West African CFA Franc1.00\", \"Central African CFA Franc1.00\", \"West African CFA franc1.00\", \"Central African CFA franc1.00\", \"West African CFA francs1.00\", \"Central African CFA francs1.00\", \"CFP Franc1.00\", \"CFP franc1.00\", \"CFP francs1.00\", \"CFPF1.00\", \"CHE1.00\", \"CHE1.00\", \"CHF1.00\", \"CHW1.00\", \"CHW1.00\", \"CLF1.00\", \"CLF1.00\", \"CLP1.00\", \"CNY1.00\", \"COP1.00\", \"COU1.00\", \"COU1.00\", \"CRC1.00\", \"CSD1.00\", \"CSD1.00\", \"CSK1.00\", \"CSK1.00\", \"CUP1.00\", \"CUP1.00\", \"CVE1.00\", \"CYP1.00\", \"CZK1.00\", \"Cambodian Riel1.00\", \"Cambodian riel1.00\", \"Cambodian riels1.00\", \"Canadian Dollar1.00\", \"Canadian dollar1.00\", \"Canadian dollars1.00\", \"Cape Verdean Escudo1.00\", \"Cape Verdean escudo1.00\", \"Cape Verdean escudos1.00\", \"Cayman Islands Dollar1.00\", \"Cayman Islands dollar1.00\", \"Cayman Islands dollars1.00\", \"Chilean Peso1.00\", \"Chilean Unit of Account (UF)1.00\", \"Chilean peso1.00\", \"Chilean pesos1.00\", \"Chilean unit of account (UF)1.00\", \"Chilean units of account (UF)1.00\", \"Chinese Yuan1.00\", \"Chinese yuan1.00\", \"Colombian Peso1.00\", \"Colombian peso1.00\", \"Colombian pesos1.00\", \"Comorian Franc1.00\", \"Comorian franc1.00\", \"Comorian francs1.00\", \"Congolese Franc1.00\", \"Congolese franc1.00\", \"Congolese francs1.00\", \"Costa Rican Col\\\\u00f3n1.00\", \"Costa Rican col\\\\u00f3n1.00\", \"Costa Rican col\\\\u00f3ns1.00\", \"Croatian Dinar1.00\", \"Croatian Kuna1.00\", \"Croatian dinar1.00\", \"Croatian dinars1.00\", \"Croatian kuna1.00\", \"Croatian kunas1.00\", \"Cuban Peso1.00\", \"Cuban peso1.00\", \"Cuban pesos1.00\", \"Cypriot Pound1.00\", \"Cypriot pound1.00\", \"Cypriot pounds1.00\", \"Czech Koruna1.00\", \"Czech koruna1.00\", \"Czech korunas1.00\", \"Czechoslovak Hard Koruna1.00\", \"Czechoslovak hard koruna1.00\", \"Czechoslovak hard korunas1.00\", \"DDM1.00\", \"DDM1.00\", \"DEM1.00\", \"DEM1.00\", \"DJF1.00\", \"DKK1.00\", \"DOP1.00\", \"DZD1.00\", \"Danish Krone1.00\", \"Danish krone1.00\", \"Danish kroner1.00\", \"German Mark1.00\", \"German mark1.00\", \"German marks1.00\", \"Djiboutian Franc1.00\", \"Djiboutian franc1.00\", \"Djiboutian francs1.00\", \"Dominican Peso1.00\", \"Dominican peso1.00\", \"Dominican pesos1.00\", \"EC$1.00\", \"ECS1.00\", \"ECS1.00\", \"ECV1.00\", \"ECV1.00\", \"EEK1.00\", \"EEK1.00\", \"EGP1.00\", \"EGP1.00\", \"ERN1.00\", \"ERN1.00\", \"ESA1.00\", \"ESA1.00\", \"ESB1.00\", \"ESB1.00\", \"ESP1.00\", \"ETB1.00\", \"EUR1.00\", \"East Caribbean Dollar1.00\", \"East Caribbean dollar1.00\", \"East Caribbean dollars1.00\", \"East German Mark1.00\", \"East German mark1.00\", \"East German marks1.00\", \"Ecuadorian Sucre1.00\", \"Ecuadorian Unit of Constant Value1.00\", \"Ecuadorian sucre1.00\", \"Ecuadorian sucres1.00\", \"Ecuadorian unit of constant value1.00\", \"Ecuadorian units of constant value1.00\", \"Egyptian Pound1.00\", \"Egyptian pound1.00\", \"Egyptian pounds1.00\", \"Salvadoran Col\\\\u00f3n1.00\", \"Salvadoran col\\\\u00f3n1.00\", \"Salvadoran colones1.00\", \"Equatorial Guinean Ekwele1.00\", \"Equatorial Guinean ekwele1.00\", \"Eritrean Nakfa1.00\", \"Eritrean nakfa1.00\", \"Eritrean nakfas1.00\", \"Estonian Kroon1.00\", \"Estonian kroon1.00\", \"Estonian kroons1.00\", \"Ethiopian Birr1.00\", \"Ethiopian birr1.00\", \"Ethiopian birrs1.00\", \"Euro1.00\", \"European Composite Unit1.00\", \"European Currency Unit1.00\", \"European Monetary Unit1.00\", \"European Unit of Account (XBC)1.00\", \"European Unit of Account (XBD)1.00\", \"European composite unit1.00\", \"European composite units1.00\", \"European currency unit1.00\", \"European currency units1.00\", \"European monetary unit1.00\", \"European monetary units1.00\", \"European unit of account (XBC)1.00\", \"European unit of account (XBD)1.00\", \"European units of account (XBC)1.00\", \"European units of account (XBD)1.00\", \"FIM1.00\", \"FIM1.00\", \"FJD1.00\", \"FKP1.00\", \"FKP1.00\", \"FRF1.00\", \"FRF1.00\", \"Falkland Islands Pound1.00\", \"Falkland Islands pound1.00\", \"Falkland Islands pounds1.00\", \"Fijian Dollar1.00\", \"Fijian dollar1.00\", \"Fijian dollars1.00\", \"Finnish Markka1.00\", \"Finnish markka1.00\", \"Finnish markkas1.00\", \"CHF1.00\", \"French Franc1.00\", \"French Gold Franc1.00\", \"French UIC-Franc1.00\", \"French UIC-franc1.00\", \"French UIC-francs1.00\", \"French franc1.00\", \"French francs1.00\", \"French gold franc1.00\", \"French gold francs1.00\", \"GBP1.00\", \"GEK1.00\", \"GEK1.00\", \"GEL1.00\", \"GHC1.00\", \"GHC1.00\", \"GHS1.00\", \"GIP1.00\", \"GIP1.00\", \"GMD1.00\", \"GMD1.00\", \"GNF1.00\", \"GNS1.00\", \"GNS1.00\", \"GQE1.00\", \"GQE1.00\", \"GRD1.00\", \"GRD1.00\", \"GTQ1.00\", \"GWE1.00\", \"GWE1.00\", \"GWP1.00\", \"GWP1.00\", \"GYD1.00\", \"Gambian Dalasi1.00\", \"Gambian dalasi1.00\", \"Gambian dalasis1.00\", \"Georgian Kupon Larit1.00\", \"Georgian Lari1.00\", \"Georgian kupon larit1.00\", \"Georgian kupon larits1.00\", \"Georgian lari1.00\", \"Georgian laris1.00\", \"Ghanaian Cedi (1979\\\\u20132007)1.00\", \"Ghanaian Cedi1.00\", \"Ghanaian cedi (1979\\\\u20132007)1.00\", \"Ghanaian cedi1.00\", \"Ghanaian cedis (1979\\\\u20132007)1.00\", \"Ghanaian cedis1.00\", \"Gibraltar Pound1.00\", \"Gibraltar pound1.00\", \"Gibraltar pounds1.00\", \"Gold1.00\", \"Gold1.00\", \"Greek Drachma1.00\", \"Greek drachma1.00\", \"Greek drachmas1.00\", \"Guatemalan Quetzal1.00\", \"Guatemalan quetzal1.00\", \"Guatemalan quetzals1.00\", \"Guinean Franc1.00\", \"Guinean Syli1.00\", \"Guinean franc1.00\", \"Guinean francs1.00\", \"Guinean syli1.00\", \"Guinean sylis1.00\", \"Guinea-Bissau Peso1.00\", \"Guinea-Bissau peso1.00\", \"Guinea-Bissau pesos1.00\", \"Guyanaese Dollar1.00\", \"Guyanaese dollar1.00\", \"Guyanaese dollars1.00\", \"HK$1.00\", \"HKD1.00\", \"HNL1.00\", \"HRD1.00\", \"HRD1.00\", \"HRK1.00\", \"HRK1.00\", \"HTG1.00\", \"HTG1.00\", \"HUF1.00\", \"Haitian Gourde1.00\", \"Haitian gourde1.00\", \"Haitian gourdes1.00\", \"Honduran Lempira1.00\", \"Honduran lempira1.00\", \"Honduran lempiras1.00\", \"Hong Kong Dollar1.00\", \"Hong Kong dollar1.00\", \"Hong Kong dollars1.00\", \"Hungarian Forint1.00\", \"Hungarian forint1.00\", \"Hungarian forints1.00\", \"IDR1.00\", \"IEP1.00\", \"ILP1.00\", \"ILP1.00\", \"ILS1.00\", \"INR1.00\", \"IQD1.00\", \"IRR1.00\", \"ISK1.00\", \"ISK1.00\", \"ITL1.00\", \"Icelandic Kr\\\\u00f3na1.00\", \"Icelandic kr\\\\u00f3na1.00\", \"Icelandic kr\\\\u00f3nur1.00\", \"Indian Rupee1.00\", \"Indian rupee1.00\", \"Indian rupees1.00\", \"Indonesian Rupiah1.00\", \"Indonesian rupiah1.00\", \"Indonesian rupiahs1.00\", \"Iranian Rial1.00\", \"Iranian rial1.00\", \"Iranian rials1.00\", \"Iraqi Dinar1.00\", \"Iraqi dinar1.00\", \"Iraqi dinars1.00\", \"Irish Pound1.00\", \"Irish pound1.00\", \"Irish pounds1.00\", \"Israeli Pound1.00\", \"Israeli new shekel1.00\", \"Israeli pound1.00\", \"Israeli pounds1.00\", \"Italian Lira1.00\", \"Italian lira1.00\", \"Italian liras1.00\", \"JMD1.00\", \"JOD1.00\", \"JPY1.00\", \"Jamaican Dollar1.00\", \"Jamaican dollar1.00\", \"Jamaican dollars1.00\", \"Japanese Yen1.00\", \"Japanese yen1.00\", \"Jordanian Dinar1.00\", \"Jordanian dinar1.00\", \"Jordanian dinars1.00\", \"KES1.00\", \"KGS1.00\", \"KHR1.00\", \"KMF1.00\", \"KPW1.00\", \"KPW1.00\", \"KRW1.00\", \"KWD1.00\", \"KYD1.00\", \"KYD1.00\", \"KZT1.00\", \"Kazakhstani Tenge1.00\", \"Kazakhstani tenge1.00\", \"Kazakhstani tenges1.00\", \"Kenyan Shilling1.00\", \"Kenyan shilling1.00\", \"Kenyan shillings1.00\", \"Kuwaiti Dinar1.00\", \"Kuwaiti dinar1.00\", \"Kuwaiti dinars1.00\", \"Kyrgystani Som1.00\", \"Kyrgystani som1.00\", \"Kyrgystani soms1.00\", \"HNL1.00\", \"LAK1.00\", \"LAK1.00\", \"LBP1.00\", \"LKR1.00\", \"LRD1.00\", \"LRD1.00\", \"LSL1.00\", \"LTL1.00\", \"LTL1.00\", \"LTT1.00\", \"LTT1.00\", \"LUC1.00\", \"LUC1.00\", \"LUF1.00\", \"LUF1.00\", \"LUL1.00\", \"LUL1.00\", \"LVL1.00\", \"LVL1.00\", \"LVR1.00\", \"LVR1.00\", \"LYD1.00\", \"Laotian Kip1.00\", \"Laotian kip1.00\", \"Laotian kips1.00\", \"Latvian Lats1.00\", \"Latvian Ruble1.00\", \"Latvian lats1.00\", \"Latvian lati1.00\", \"Latvian ruble1.00\", \"Latvian rubles1.00\", \"Lebanese Pound1.00\", \"Lebanese pound1.00\", \"Lebanese pounds1.00\", \"Lesotho Loti1.00\", \"Lesotho loti1.00\", \"Lesotho lotis1.00\", \"Liberian Dollar1.00\", \"Liberian dollar1.00\", \"Liberian dollars1.00\", \"Libyan Dinar1.00\", \"Libyan dinar1.00\", \"Libyan dinars1.00\", \"Lithuanian Litas1.00\", \"Lithuanian Talonas1.00\", \"Lithuanian litas1.00\", \"Lithuanian litai1.00\", \"Lithuanian talonas1.00\", \"Lithuanian talonases1.00\", \"Luxembourgian Convertible Franc1.00\", \"Luxembourg Financial Franc1.00\", \"Luxembourgian Franc1.00\", \"Luxembourgian convertible franc1.00\", \"Luxembourgian convertible francs1.00\", \"Luxembourg financial franc1.00\", \"Luxembourg financial francs1.00\", \"Luxembourgian franc1.00\", \"Luxembourgian francs1.00\", \"MAD1.00\", \"MAD1.00\", \"MAF1.00\", \"MAF1.00\", \"MDL1.00\", \"MDL1.00\", \"MX$1.00\", \"MGA1.00\", \"MGA1.00\", \"MGF1.00\", \"MGF1.00\", \"MKD1.00\", \"MLF1.00\", \"MLF1.00\", \"MMK1.00\", \"MMK1.00\", \"MNT1.00\", \"MOP1.00\", \"MOP1.00\", \"MRO1.00\", \"MTL1.00\", \"MTP1.00\", \"MTP1.00\", \"MUR1.00\", \"MUR1.00\", \"MVR1.00\", \"MVR1.00\", \"MWK1.00\", \"MXN1.00\", \"MXP1.00\", \"MXP1.00\", \"MXV1.00\", \"MXV1.00\", \"MYR1.00\", \"MZE1.00\", \"MZE1.00\", \"MZM1.00\", \"MZN1.00\", \"Macanese Pataca1.00\", \"Macanese pataca1.00\", \"Macanese patacas1.00\", \"Macedonian Denar1.00\", \"Macedonian denar1.00\", \"Macedonian denari1.00\", \"Malagasy Ariaries1.00\", \"Malagasy Ariary1.00\", \"Malagasy Ariary1.00\", \"Malagasy Franc1.00\", \"Malagasy franc1.00\", \"Malagasy francs1.00\", \"Malawian Kwacha1.00\", \"Malawian Kwacha1.00\", \"Malawian Kwachas1.00\", \"Malaysian Ringgit1.00\", \"Malaysian ringgit1.00\", \"Malaysian ringgits1.00\", \"Maldivian Rufiyaa1.00\", \"Maldivian rufiyaa1.00\", \"Maldivian rufiyaas1.00\", \"Malian Franc1.00\", \"Malian franc1.00\", \"Malian francs1.00\", \"Maltese Lira1.00\", \"Maltese Pound1.00\", \"Maltese lira1.00\", \"Maltese lira1.00\", \"Maltese pound1.00\", \"Maltese pounds1.00\", \"Mauritanian Ouguiya1.00\", \"Mauritanian ouguiya1.00\", \"Mauritanian ouguiyas1.00\", \"Mauritian Rupee1.00\", \"Mauritian rupee1.00\", \"Mauritian rupees1.00\", \"Mexican Peso1.00\", \"Mexican Silver Peso (1861\\\\u20131992)1.00\", \"Mexican Investment Unit1.00\", \"Mexican peso1.00\", \"Mexican pesos1.00\", \"Mexican silver peso (1861\\\\u20131992)1.00\", \"Mexican silver pesos (1861\\\\u20131992)1.00\", \"Mexican investment unit1.00\", \"Mexican investment units1.00\", \"Moldovan Leu1.00\", \"Moldovan leu1.00\", \"Moldovan lei1.00\", \"Mongolian Tugrik1.00\", \"Mongolian tugrik1.00\", \"Mongolian tugriks1.00\", \"Moroccan Dirham1.00\", \"Moroccan Franc1.00\", \"Moroccan dirham1.00\", \"Moroccan dirhams1.00\", \"Moroccan franc1.00\", \"Moroccan francs1.00\", \"Mozambican Escudo1.00\", \"Mozambican Metical1.00\", \"Mozambican escudo1.00\", \"Mozambican escudos1.00\", \"Mozambican metical1.00\", \"Mozambican meticals1.00\", \"Myanmar Kyat1.00\", \"Myanmar kyat1.00\", \"Myanmar kyats1.00\", \"NAD1.00\", \"NGN1.00\", \"NIC1.00\", \"NIO1.00\", \"NIO1.00\", \"NLG1.00\", \"NLG1.00\", \"NOK1.00\", \"NPR1.00\", \"NT$1.00\", \"NZ$1.00\", \"NZD1.00\", \"Namibian Dollar1.00\", \"Namibian dollar1.00\", \"Namibian dollars1.00\", \"Nepalese Rupee1.00\", \"Nepalese rupee1.00\", \"Nepalese rupees1.00\", \"Netherlands Antillean Guilder1.00\", \"Netherlands Antillean guilder1.00\", \"Netherlands Antillean guilders1.00\", \"Dutch Guilder1.00\", \"Dutch guilder1.00\", \"Dutch guilders1.00\", \"Israeli New Shekel1.00\", \"Israeli New Shekels1.00\", \"New Zealand Dollar1.00\", \"New Zealand dollar1.00\", \"New Zealand dollars1.00\", \"Nicaraguan C\\\\u00f3rdoba1.00\", \"Nicaraguan C\\\\u00f3rdoba (1988\\\\u20131991)1.00\", \"Nicaraguan c\\\\u00f3rdoba1.00\", \"Nicaraguan c\\\\u00f3rdobas1.00\", \"Nicaraguan c\\\\u00f3rdoba (1988\\\\u20131991)1.00\", \"Nicaraguan c\\\\u00f3rdobas (1988\\\\u20131991)1.00\", \"Nigerian Naira1.00\", \"Nigerian naira1.00\", \"Nigerian nairas1.00\", \"North Korean Won1.00\", \"North Korean won1.00\", \"North Korean won1.00\", \"Norwegian Krone1.00\", \"Norwegian krone1.00\", \"Norwegian kroner1.00\", \"OMR1.00\", \"Mozambican Metical (1980\\\\u20132006)1.00\", \"Mozambican metical (1980\\\\u20132006)1.00\", \"Mozambican meticals (1980\\\\u20132006)1.00\", \"Romanian Lei (1952\\\\u20132006)1.00\", \"Romanian Leu (1952\\\\u20132006)1.00\", \"Romanian leu (1952\\\\u20132006)1.00\", \"Serbian Dinar (2002\\\\u20132006)1.00\", \"Serbian dinar (2002\\\\u20132006)1.00\", \"Serbian dinars (2002\\\\u20132006)1.00\", \"Sudanese Dinar (1992\\\\u20132007)1.00\", \"Sudanese Pound (1957\\\\u20131998)1.00\", \"Sudanese dinar (1992\\\\u20132007)1.00\", \"Sudanese dinars (1992\\\\u20132007)1.00\", \"Sudanese pound (1957\\\\u20131998)1.00\", \"Sudanese pounds (1957\\\\u20131998)1.00\", \"Turkish Lira (1922\\\\u20132005)1.00\", \"Turkish Lira (1922\\\\u20132005)1.00\", \"Omani Rial1.00\", \"Omani rial1.00\", \"Omani rials1.00\", \"PAB1.00\", \"PAB1.00\", \"PEI1.00\", \"PEI1.00\", \"PEN1.00\", \"PEN1.00\", \"PES1.00\", \"PES1.00\", \"PGK1.00\", \"PGK1.00\", \"PHP1.00\", \"PKR1.00\", \"PLN1.00\", \"PLZ1.00\", \"PLZ1.00\", \"PTE1.00\", \"PTE1.00\", \"PYG1.00\", \"Pakistani Rupee1.00\", \"Pakistani rupee1.00\", \"Pakistani rupees1.00\", \"Palladium1.00\", \"Palladium1.00\", \"Panamanian Balboa1.00\", \"Panamanian balboa1.00\", \"Panamanian balboas1.00\", \"Papua New Guinean Kina1.00\", \"Papua New Guinean kina1.00\", \"Papua New Guinean kina1.00\", \"Paraguayan Guarani1.00\", \"Paraguayan guarani1.00\", \"Paraguayan guaranis1.00\", \"Peruvian Inti1.00\", \"Peruvian Sol1.00\", \"Peruvian Sol (1863\\\\u20131965)1.00\", \"Peruvian inti1.00\", \"Peruvian intis1.00\", \"Peruvian sol1.00\", \"Peruvian soles1.00\", \"Peruvian sol (1863\\\\u20131965)1.00\", \"Peruvian soles (1863\\\\u20131965)1.00\", \"Philippine Piso1.00\", \"Philippine piso1.00\", \"Philippine pisos1.00\", \"Platinum1.00\", \"Platinum1.00\", \"Polish Zloty (1950\\\\u20131995)1.00\", \"Polish Zloty1.00\", \"Polish zlotys1.00\", \"Polish zloty (PLZ)1.00\", \"Polish zloty1.00\", \"Polish zlotys (PLZ)1.00\", \"Portuguese Escudo1.00\", \"Portuguese Guinea Escudo1.00\", \"Portuguese Guinea escudo1.00\", \"Portuguese Guinea escudos1.00\", \"Portuguese escudo1.00\", \"Portuguese escudos1.00\", \"GTQ1.00\", \"QAR1.00\", \"Qatari Rial1.00\", \"Qatari rial1.00\", \"Qatari rials1.00\", \"RHD1.00\", \"RHD1.00\", \"RINET Funds1.00\", \"RINET Funds1.00\", \"CN\\\\u00a51.00\", \"ROL1.00\", \"ROL1.00\", \"RON1.00\", \"RON1.00\", \"RSD1.00\", \"RSD1.00\", \"RUB1.00\", \"RUR1.00\", \"RUR1.00\", \"RWF1.00\", \"RWF1.00\", \"Rhodesian Dollar1.00\", \"Rhodesian dollar1.00\", \"Rhodesian dollars1.00\", \"Romanian Leu1.00\", \"Romanian lei1.00\", \"Romanian leu1.00\", \"Russian Ruble (1991\\\\u20131998)1.00\", \"Russian Ruble1.00\", \"Russian ruble (1991\\\\u20131998)1.00\", \"Russian ruble1.00\", \"Russian rubles (1991\\\\u20131998)1.00\", \"Russian rubles1.00\", \"Rwandan Franc1.00\", \"Rwandan franc1.00\", \"Rwandan francs1.00\", \"SAR1.00\", \"SBD1.00\", \"SCR1.00\", \"SDD1.00\", \"SDD1.00\", \"SDG1.00\", \"SDG1.00\", \"SDP1.00\", \"SDP1.00\", \"SEK1.00\", \"SGD1.00\", \"SHP1.00\", \"SHP1.00\", \"SIT1.00\", \"SIT1.00\", \"SKK1.00\", \"SLL1.00\", \"SLL1.00\", \"SOS1.00\", \"SRD1.00\", \"SRD1.00\", \"SRG1.00\", \"STD1.00\", \"SUR1.00\", \"SUR1.00\", \"SVC1.00\", \"SVC1.00\", \"SYP1.00\", \"SZL1.00\", \"St. Helena Pound1.00\", \"St. Helena pound1.00\", \"St. Helena pounds1.00\", \"S\\\\u00e3o Tom\\\\u00e9 & Pr\\\\u00edncipe Dobra1.00\", \"S\\\\u00e3o Tom\\\\u00e9 & Pr\\\\u00edncipe dobra1.00\", \"S\\\\u00e3o Tom\\\\u00e9 & Pr\\\\u00edncipe dobras1.00\", \"Saudi Riyal1.00\", \"Saudi riyal1.00\", \"Saudi riyals1.00\", \"Serbian Dinar1.00\", \"Serbian dinar1.00\", \"Serbian dinars1.00\", \"Seychellois Rupee1.00\", \"Seychellois rupee1.00\", \"Seychellois rupees1.00\", \"Sierra Leonean Leone1.00\", \"Sierra Leonean leone1.00\", \"Sierra Leonean leones1.00\", \"Silver1.00\", \"Silver1.00\", \"Singapore Dollar1.00\", \"Singapore dollar1.00\", \"Singapore dollars1.00\", \"Slovak Koruna1.00\", \"Slovak koruna1.00\", \"Slovak korunas1.00\", \"Slovenian Tolar1.00\", \"Slovenian tolar1.00\", \"Slovenian tolars1.00\", \"Solomon Islands Dollar1.00\", \"Solomon Islands dollar1.00\", \"Solomon Islands dollars1.00\", \"Somali Shilling1.00\", \"Somali shilling1.00\", \"Somali shillings1.00\", \"South African Rand (financial)1.00\", \"South African Rand1.00\", \"South African rand (financial)1.00\", \"South African rand1.00\", \"South African rands (financial)1.00\", \"South African rand1.00\", \"South Korean Won1.00\", \"South Korean won1.00\", \"South Korean won1.00\", \"Soviet Rouble1.00\", \"Soviet rouble1.00\", \"Soviet roubles1.00\", \"Spanish Peseta (A account)1.00\", \"Spanish Peseta (convertible account)1.00\", \"Spanish Peseta1.00\", \"Spanish peseta (A account)1.00\", \"Spanish peseta (convertible account)1.00\", \"Spanish peseta1.00\", \"Spanish pesetas (A account)1.00\", \"Spanish pesetas (convertible account)1.00\", \"Spanish pesetas1.00\", \"Special Drawing Rights1.00\", \"Sri Lankan Rupee1.00\", \"Sri Lankan rupee1.00\", \"Sri Lankan rupees1.00\", \"Sudanese Pound1.00\", \"Sudanese pound1.00\", \"Sudanese pounds1.00\", \"Surinamese Dollar1.00\", \"Surinamese dollar1.00\", \"Surinamese dollars1.00\", \"Surinamese Guilder1.00\", \"Surinamese guilder1.00\", \"Surinamese guilders1.00\", \"Swazi Lilangeni1.00\", \"Swazi lilangeni1.00\", \"Swazi emalangeni1.00\", \"Swedish Krona1.00\", \"Swedish krona1.00\", \"Swedish kronor1.00\", \"Swiss Franc1.00\", \"Swiss franc1.00\", \"Swiss francs1.00\", \"Syrian Pound1.00\", \"Syrian pound1.00\", \"Syrian pounds1.00\", \"THB1.00\", \"TJR1.00\", \"TJR1.00\", \"TJS1.00\", \"TJS1.00\", \"TMM1.00\", \"TMM1.00\", \"TND1.00\", \"TND1.00\", \"TOP1.00\", \"TPE1.00\", \"TPE1.00\", \"TRL1.00\", \"TRY1.00\", \"TRY1.00\", \"TTD1.00\", \"TWD1.00\", \"TZS1.00\", \"New Taiwan Dollar1.00\", \"New Taiwan dollar1.00\", \"New Taiwan dollars1.00\", \"Tajikistani Ruble1.00\", \"Tajikistani Somoni1.00\", \"Tajikistani ruble1.00\", \"Tajikistani rubles1.00\", \"Tajikistani somoni1.00\", \"Tajikistani somonis1.00\", \"Tanzanian Shilling1.00\", \"Tanzanian shilling1.00\", \"Tanzanian shillings1.00\", \"Testing Currency Code1.00\", \"Testing Currency Code1.00\", \"Thai Baht1.00\", \"Thai baht1.00\", \"Thai baht1.00\", \"Timorese Escudo1.00\", \"Timorese escudo1.00\", \"Timorese escudos1.00\", \"Tongan Pa\\\\u02bbanga1.00\", \"Tongan pa\\\\u02bbanga1.00\", \"Tongan pa\\\\u02bbanga1.00\", \"Trinidad & Tobago Dollar1.00\", \"Trinidad & Tobago dollar1.00\", \"Trinidad & Tobago dollars1.00\", \"Tunisian Dinar1.00\", \"Tunisian dinar1.00\", \"Tunisian dinars1.00\", \"Turkish Lira1.00\", \"Turkish Lira1.00\", \"Turkish lira1.00\", \"Turkmenistani Manat1.00\", \"Turkmenistani manat1.00\", \"Turkmenistani manat1.00\", \"UAE dirham1.00\", \"UAE dirhams1.00\", \"UAH1.00\", \"UAK1.00\", \"UAK1.00\", \"UGS1.00\", \"UGS1.00\", \"UGX1.00\", \"US Dollar (Next day)1.00\", \"US Dollar (Same day)1.00\", \"US Dollar1.00\", \"US dollar (next day)1.00\", \"US dollar (same day)1.00\", \"US dollar1.00\", \"US dollars (next day)1.00\", \"US dollars (same day)1.00\", \"US dollars1.00\", \"USD1.00\", \"USN1.00\", \"USN1.00\", \"USS1.00\", \"USS1.00\", \"UYI1.00\", \"UYI1.00\", \"UYP1.00\", \"UYP1.00\", \"UYU1.00\", \"UZS1.00\", \"UZS1.00\", \"Ugandan Shilling (1966\\\\u20131987)1.00\", \"Ugandan Shilling1.00\", \"Ugandan shilling (1966\\\\u20131987)1.00\", \"Ugandan shilling1.00\", \"Ugandan shillings (1966\\\\u20131987)1.00\", \"Ugandan shillings1.00\", \"Ukrainian Hryvnia1.00\", \"Ukrainian Karbovanets1.00\", \"Ukrainian hryvnia1.00\", \"Ukrainian hryvnias1.00\", \"Ukrainian karbovanets1.00\", \"Ukrainian karbovantsiv1.00\", \"Colombian Real Value Unit1.00\", \"United Arab Emirates Dirham1.00\", \"Unknown Currency1.00\", \"Uruguayan Peso (1975\\\\u20131993)1.00\", \"Uruguayan Peso1.00\", \"Uruguayan Peso (Indexed Units)1.00\", \"Uruguayan peso (1975\\\\u20131993)1.00\", \"Uruguayan peso (indexed units)1.00\", \"Uruguayan peso1.00\", \"Uruguayan pesos (1975\\\\u20131993)1.00\", \"Uruguayan pesos (indexed units)1.00\", \"Uruguayan pesos1.00\", \"Uzbekistani Som1.00\", \"Uzbekistani som1.00\", \"Uzbekistani som1.00\", \"VEB1.00\", \"VEF1.00\", \"VND1.00\", \"VUV1.00\", \"Vanuatu Vatu1.00\", \"Vanuatu vatu1.00\", \"Vanuatu vatus1.00\", \"Venezuelan Bol\\\\u00edvar1.00\", \"Venezuelan Bol\\\\u00edvar (1871\\\\u20132008)1.00\", \"Venezuelan bol\\\\u00edvar1.00\", \"Venezuelan bol\\\\u00edvars1.00\", \"Venezuelan bol\\\\u00edvar (1871\\\\u20132008)1.00\", \"Venezuelan bol\\\\u00edvars (1871\\\\u20132008)1.00\", \"Vietnamese Dong1.00\", \"Vietnamese dong1.00\", \"Vietnamese dong1.00\", \"WIR Euro1.00\", \"WIR Franc1.00\", \"WIR euro1.00\", \"WIR euros1.00\", \"WIR franc1.00\", \"WIR francs1.00\", \"WST1.00\", \"WST1.00\", \"Samoan Tala1.00\", \"Samoan tala1.00\", \"Samoan tala1.00\", \"XAF1.00\", \"XAF1.00\", \"XAG1.00\", \"XAG1.00\", \"XAU1.00\", \"XAU1.00\", \"XBA1.00\", \"XBA1.00\", \"XBB1.00\", \"XBB1.00\", \"XBC1.00\", \"XBC1.00\", \"XBD1.00\", \"XBD1.00\", \"XCD1.00\", \"XDR1.00\", \"XDR1.00\", \"XEU1.00\", \"XEU1.00\", \"XFO1.00\", \"XFO1.00\", \"XFU1.00\", \"XFU1.00\", \"XOF1.00\", \"XOF1.00\", \"XPD1.00\", \"XPD1.00\", \"XPF1.00\", \"XPT1.00\", \"XPT1.00\", \"XRE1.00\", \"XRE1.00\", \"XTS1.00\", \"XTS1.00\", \"XXX1.00\", \"XXX1.00\", \"YDD1.00\", \"YDD1.00\", \"YER1.00\", \"YUD1.00\", \"YUD1.00\", \"YUM1.00\", \"YUM1.00\", \"YUN1.00\", \"YUN1.00\", \"Yemeni Dinar1.00\", \"Yemeni Rial1.00\", \"Yemeni dinar1.00\", \"Yemeni dinars1.00\", \"Yemeni rial1.00\", \"Yemeni rials1.00\", \"Yugoslavian Convertible Dinar (1990\\\\u20131992)1.00\", \"Yugoslavian Hard Dinar (1966\\\\u20131990)1.00\", \"Yugoslavian New Dinar (1994\\\\u20132002)1.00\", \"Yugoslavian convertible dinar (1990\\\\u20131992)1.00\", \"Yugoslavian convertible dinars (1990\\\\u20131992)1.00\", \"Yugoslavian hard dinar (1966\\\\u20131990)1.00\", \"Yugoslavian hard dinars (1966\\\\u20131990)1.00\", \"Yugoslavian new dinar (1994\\\\u20132002)1.00\", \"Yugoslavian new dinars (1994\\\\u20132002)1.00\", \"ZAL1.00\", \"ZAL1.00\", \"ZAR1.00\", \"ZMK1.00\", \"ZMK1.00\", \"ZRN1.00\", \"ZRN1.00\", \"ZRZ1.00\", \"ZRZ1.00\", \"ZWD1.00\", \"Zairean New Zaire (1993\\\\u20131998)1.00\", \"Zairean Zaire (1971\\\\u20131993)1.00\", \"Zairean new zaire (1993\\\\u20131998)1.00\", \"Zairean new zaires (1993\\\\u20131998)1.00\", \"Zairean zaire (1971\\\\u20131993)1.00\", \"Zairean zaires (1971\\\\u20131993)1.00\", \"Zambian Kwacha1.00\", \"Zambian kwacha1.00\", \"Zambian kwachas1.00\", \"Zimbabwean Dollar (1980\\\\u20132008)1.00\", \"Zimbabwean dollar (1980\\\\u20132008)1.00\", \"Zimbabwean dollars (1980\\\\u20132008)1.00\", \"euro1.00\", \"euros1.00\", \"Turkish lira (1922\\\\u20132005)1.00\", \"special drawing rights1.00\", \"Colombian real value unit1.00\", \"Colombian real value units1.00\", \"unknown currency1.00\", \"\\\\u00a31.00\", \"\\\\u00a51.00\", \"\\\\u20ab1.00\", \"\\\\u20aa1.00\", \"\\\\u20ac1.00\", \"\\\\u20b91.00\", \/\/ \/\/ Following has extra text, should be parsed correctly too \"$1.00 random\", \"USD1.00 random\", \"1.00 US dollar random\", \"1.00 US dollars random\", \"1.00 Afghan Afghani random\", \"1.00 Afghan Afghani random\", \"1.00 Afghan Afghanis (1927\\\\u20131992) random\", \"1.00 Afghan Afghanis random\", \"1.00 Albanian Lek random\", \"1.00 Albanian lek random\", \"1.00 Albanian lek\\\\u00eb random\", \"1.00 Algerian Dinar random\", \"1.00 Algerian dinar random\", \"1.00 Algerian dinars random\", \"1.00 Andorran Peseta random\", \"1.00 Andorran peseta random\", \"1.00 Andorran pesetas random\", \"1.00 Angolan Kwanza (1977\\\\u20131990) random\", \"1.00 Angolan Readjusted Kwanza (1995\\\\u20131999) random\", \"1.00 Angolan Kwanza random\", \"1.00 Angolan New Kwanza (1990\\\\u20132000) random\", \"1.00 Angolan kwanza (1977\\\\u20131991) random\", \"1.00 Angolan readjusted kwanza (1995\\\\u20131999) random\", \"1.00 Angolan kwanza random\", \"1.00 Angolan kwanzas (1977\\\\u20131991) random\", \"1.00 Angolan readjusted kwanzas (1995\\\\u20131999) random\", \"1.00 Angolan kwanzas random\", \"1.00 Angolan new kwanza (1990\\\\u20132000) random\", \"1.00 Angolan new kwanzas (1990\\\\u20132000) random\", \"1.00 Argentine Austral random\", \"1.00 Argentine Peso (1983\\\\u20131985) random\", \"1.00 Argentine Peso random\", \"1.00 Argentine austral random\", \"1.00 Argentine australs random\", \"1.00 Argentine peso (1983\\\\u20131985) random\", \"1.00 Argentine peso random\", \"1.00 Argentine pesos (1983\\\\u20131985) random\", \"1.00 Argentine pesos random\", \"1.00 Armenian Dram random\", \"1.00 Armenian dram random\", \"1.00 Armenian drams random\", \"1.00 Aruban Florin random\", \"1.00 Aruban florin random\", \"1.00 Australian Dollar random\", \"1.00 Australian dollar random\", \"1.00 Australian dollars random\", \"1.00 Austrian Schilling random\", \"1.00 Austrian schilling random\", \"1.00 Austrian schillings random\", \"1.00 Azerbaijani Manat (1993\\\\u20132006) random\", \"1.00 Azerbaijani Manat random\", \"1.00 Azerbaijani manat (1993\\\\u20132006) random\", \"1.00 Azerbaijani manat random\", \"1.00 Azerbaijani manats (1993\\\\u20132006) random\", \"1.00 Azerbaijani manats random\", \"1.00 Bahamian Dollar random\", \"1.00 Bahamian dollar random\", \"1.00 Bahamian dollars random\", \"1.00 Bahraini Dinar random\", \"1.00 Bahraini dinar random\", \"1.00 Bahraini dinars random\", \"1.00 Bangladeshi Taka random\", \"1.00 Bangladeshi taka random\", \"1.00 Bangladeshi takas random\", \"1.00 Barbadian Dollar random\", \"1.00 Barbadian dollar random\", \"1.00 Barbadian dollars random\", \"1.00 Belarusian Ruble (1994\\\\u20131999) random\", \"1.00 Belarusian Ruble random\", \"1.00 Belarusian ruble (1994\\\\u20131999) random\", \"1.00 Belarusian rubles (1994\\\\u20131999) random\", \"1.00 Belarusian ruble random\", \"1.00 Belarusian rubles random\", \"1.00 Belgian Franc (convertible) random\", \"1.00 Belgian Franc (financial) random\", \"1.00 Belgian Franc random\", \"1.00 Belgian franc (convertible) random\", \"1.00 Belgian franc (financial) random\", \"1.00 Belgian franc random\", \"1.00 Belgian francs (convertible) random\", \"1.00 Belgian francs (financial) random\", \"1.00 Belgian francs random\", \"1.00 Belize Dollar random\", \"1.00 Belize dollar random\", \"1.00 Belize dollars random\", \"1.00 Bermudan Dollar random\", \"1.00 Bermudan dollar random\", \"1.00 Bermudan dollars random\", \"1.00 Bhutanese Ngultrum random\", \"1.00 Bhutanese ngultrum random\", \"1.00 Bhutanese ngultrums random\", \"1.00 Bolivian Mvdol random\", \"1.00 Bolivian Peso random\", \"1.00 Bolivian mvdol random\", \"1.00 Bolivian mvdols random\", \"1.00 Bolivian peso random\", \"1.00 Bolivian pesos random\", \"1.00 Bolivian Boliviano random\", \"1.00 Bolivian Boliviano random\", \"1.00 Bolivian Bolivianos random\", \"1.00 Bosnia-Herzegovina Convertible Mark random\", \"1.00 Bosnia-Herzegovina Dinar (1992\\\\u20131994) random\", \"1.00 Bosnia-Herzegovina convertible mark random\", \"1.00 Bosnia-Herzegovina convertible marks random\", \"1.00 Bosnia-Herzegovina dinar (1992\\\\u20131994) random\", \"1.00 Bosnia-Herzegovina dinars (1992\\\\u20131994) random\", \"1.00 Botswanan Pula random\", \"1.00 Botswanan pula random\", \"1.00 Botswanan pulas random\", \"1.00 Brazilian New Cruzado (1989\\\\u20131990) random\", \"1.00 Brazilian Cruzado (1986\\\\u20131989) random\", \"1.00 Brazilian Cruzeiro (1990\\\\u20131993) random\", \"1.00 Brazilian New Cruzeiro (1967\\\\u20131986) random\", \"1.00 Brazilian Cruzeiro (1993\\\\u20131994) random\", \"1.00 Brazilian Real random\", \"1.00 Brazilian new cruzado (1989\\\\u20131990) random\", \"1.00 Brazilian new cruzados (1989\\\\u20131990) random\", \"1.00 Brazilian cruzado (1986\\\\u20131989) random\", \"1.00 Brazilian cruzados (1986\\\\u20131989) random\", \"1.00 Brazilian cruzeiro (1990\\\\u20131993) random\", \"1.00 Brazilian new cruzeiro (1967\\\\u20131986) random\", \"1.00 Brazilian cruzeiro (1993\\\\u20131994) random\", \"1.00 Brazilian cruzeiros (1990\\\\u20131993) random\", \"1.00 Brazilian new cruzeiros (1967\\\\u20131986) random\", \"1.00 Brazilian cruzeiros (1993\\\\u20131994) random\", \"1.00 Brazilian real random\", \"1.00 Brazilian reals random\", \"1.00 British Pound random\", \"1.00 British pound random\", \"1.00 British pounds random\", \"1.00 Brunei Dollar random\", \"1.00 Brunei dollar random\", \"1.00 Brunei dollars random\", \"1.00 Bulgarian Hard Lev random\", \"1.00 Bulgarian Lev random\", \"1.00 Bulgarian Leva random\", \"1.00 Bulgarian hard lev random\", \"1.00 Bulgarian hard leva random\", \"1.00 Bulgarian lev random\", \"1.00 Burmese Kyat random\", \"1.00 Burmese kyat random\", \"1.00 Burmese kyats random\", \"1.00 Burundian Franc random\", \"1.00 Burundian franc random\", \"1.00 Burundian francs random\", \"1.00 Cambodian Riel random\", \"1.00 Cambodian riel random\", \"1.00 Cambodian riels random\", \"1.00 Canadian Dollar random\", \"1.00 Canadian dollar random\", \"1.00 Canadian dollars random\", \"1.00 Cape Verdean Escudo random\", \"1.00 Cape Verdean escudo random\", \"1.00 Cape Verdean escudos random\", \"1.00 Cayman Islands Dollar random\", \"1.00 Cayman Islands dollar random\", \"1.00 Cayman Islands dollars random\", \"1.00 Chilean Peso random\", \"1.00 Chilean Unit of Account (UF) random\", \"1.00 Chilean peso random\", \"1.00 Chilean pesos random\", \"1.00 Chilean unit of account (UF) random\", \"1.00 Chilean units of account (UF) random\", \"1.00 Chinese Yuan random\", \"1.00 Chinese yuan random\", \"1.00 Colombian Peso random\", \"1.00 Colombian peso random\", \"1.00 Colombian pesos random\", \"1.00 Comorian Franc random\", \"1.00 Comorian franc random\", \"1.00 Comorian francs random\", \"1.00 Congolese Franc Congolais random\", \"1.00 Congolese franc Congolais random\", \"1.00 Congolese francs Congolais random\", \"1.00 Costa Rican Col\\\\u00f3n random\", \"1.00 Costa Rican col\\\\u00f3n random\", \"1.00 Costa Rican col\\\\u00f3ns random\", \"1.00 Croatian Dinar random\", \"1.00 Croatian Kuna random\", \"1.00 Croatian dinar random\", \"1.00 Croatian dinars random\", \"1.00 Croatian kuna random\", \"1.00 Croatian kunas random\", \"1.00 Cuban Peso random\", \"1.00 Cuban peso random\", \"1.00 Cuban pesos random\", \"1.00 Cypriot Pound random\", \"1.00 Cypriot pound random\", \"1.00 Cypriot pounds random\", \"1.00 Czech Koruna random\", \"1.00 Czech koruna random\", \"1.00 Czech korunas random\", \"1.00 Czechoslovak Hard Koruna random\", \"1.00 Czechoslovak hard koruna random\", \"1.00 Czechoslovak hard korunas random\", \"1.00 Danish Krone random\", \"1.00 Danish krone random\", \"1.00 Danish kroner random\", \"1.00 German Mark random\", \"1.00 German mark random\", \"1.00 German marks random\", \"1.00 Djiboutian Franc random\", \"1.00 Djiboutian franc random\", \"1.00 Djiboutian francs random\", \"1.00 Dominican Peso random\", \"1.00 Dominican peso random\", \"1.00 Dominican pesos random\", \"1.00 East Caribbean Dollar random\", \"1.00 East Caribbean dollar random\", \"1.00 East Caribbean dollars random\", \"1.00 East German Mark random\", \"1.00 East German mark random\", \"1.00 East German marks random\", \"1.00 Ecuadorian Sucre random\", \"1.00 Ecuadorian Unit of Constant Value random\", \"1.00 Ecuadorian sucre random\", \"1.00 Ecuadorian sucres random\", \"1.00 Ecuadorian unit of constant value random\", \"1.00 Ecuadorian units of constant value random\", \"1.00 Egyptian Pound random\", \"1.00 Egyptian pound random\", \"1.00 Egyptian pounds random\", \"1.00 Salvadoran Col\\\\u00f3n random\", \"1.00 Salvadoran col\\\\u00f3n random\", \"1.00 Salvadoran colones random\", \"1.00 Equatorial Guinean Ekwele random\", \"1.00 Equatorial Guinean ekwele random\", \"1.00 Eritrean Nakfa random\", \"1.00 Eritrean nakfa random\", \"1.00 Eritrean nakfas random\", \"1.00 Estonian Kroon random\", \"1.00 Estonian kroon random\", \"1.00 Estonian kroons random\", \"1.00 Ethiopian Birr random\", \"1.00 Ethiopian birr random\", \"1.00 Ethiopian birrs random\", \"1.00 European Composite Unit random\", \"1.00 European Currency Unit random\", \"1.00 European Monetary Unit random\", \"1.00 European Unit of Account (XBC) random\", \"1.00 European Unit of Account (XBD) random\", \"1.00 European composite unit random\", \"1.00 European composite units random\", \"1.00 European currency unit random\", \"1.00 European currency units random\", \"1.00 European monetary unit random\", \"1.00 European monetary units random\", \"1.00 European unit of account (XBC) random\", \"1.00 European unit of account (XBD) random\", \"1.00 European units of account (XBC) random\", \"1.00 European units of account (XBD) random\", \"1.00 Falkland Islands Pound random\", \"1.00 Falkland Islands pound random\", \"1.00 Falkland Islands pounds random\", \"1.00 Fijian Dollar random\", \"1.00 Fijian dollar random\", \"1.00 Fijian dollars random\", \"1.00 Finnish Markka random\", \"1.00 Finnish markka random\", \"1.00 Finnish markkas random\", \"1.00 French Franc random\", \"1.00 French Gold Franc random\", \"1.00 French UIC-Franc random\", \"1.00 French UIC-franc random\", \"1.00 French UIC-francs random\", \"1.00 French franc random\", \"1.00 French francs random\", \"1.00 French gold franc random\", \"1.00 French gold francs random\", \"1.00 Gambian Dalasi random\", \"1.00 Gambian dalasi random\", \"1.00 Gambian dalasis random\", \"1.00 Georgian Kupon Larit random\", \"1.00 Georgian Lari random\", \"1.00 Georgian kupon larit random\", \"1.00 Georgian kupon larits random\", \"1.00 Georgian lari random\", \"1.00 Georgian laris random\", \"1.00 Ghanaian Cedi (1979\\\\u20132007) random\", \"1.00 Ghanaian Cedi random\", \"1.00 Ghanaian cedi (1979\\\\u20132007) random\", \"1.00 Ghanaian cedi random\", \"1.00 Ghanaian cedis (1979\\\\u20132007) random\", \"1.00 Ghanaian cedis random\", \"1.00 Gibraltar Pound random\", \"1.00 Gibraltar pound random\", \"1.00 Gibraltar pounds random\", \"1.00 Gold random\", \"1.00 Gold random\", \"1.00 Greek Drachma random\", \"1.00 Greek drachma random\", \"1.00 Greek drachmas random\", \"1.00 Guatemalan Quetzal random\", \"1.00 Guatemalan quetzal random\", \"1.00 Guatemalan quetzals random\", \"1.00 Guinean Franc random\", \"1.00 Guinean Syli random\", \"1.00 Guinean franc random\", \"1.00 Guinean francs random\", \"1.00 Guinean syli random\", \"1.00 Guinean sylis random\", \"1.00 Guinea-Bissau Peso random\", \"1.00 Guinea-Bissau peso random\", \"1.00 Guinea-Bissau pesos random\", \"1.00 Guyanaese Dollar random\", \"1.00 Guyanaese dollar random\", \"1.00 Guyanaese dollars random\", \"1.00 Haitian Gourde random\", \"1.00 Haitian gourde random\", \"1.00 Haitian gourdes random\", \"1.00 Honduran Lempira random\", \"1.00 Honduran lempira random\", \"1.00 Honduran lempiras random\", \"1.00 Hong Kong Dollar random\", \"1.00 Hong Kong dollar random\", \"1.00 Hong Kong dollars random\", \"1.00 Hungarian Forint random\", \"1.00 Hungarian forint random\", \"1.00 Hungarian forints random\", \"1.00 Icelandic Kr\\\\u00f3na random\", \"1.00 Icelandic kr\\\\u00f3na random\", \"1.00 Icelandic kr\\\\u00f3nur random\", \"1.00 Indian Rupee random\", \"1.00 Indian rupee random\", \"1.00 Indian rupees random\", \"1.00 Indonesian Rupiah random\", \"1.00 Indonesian rupiah random\", \"1.00 Indonesian rupiahs random\", \"1.00 Iranian Rial random\", \"1.00 Iranian rial random\", \"1.00 Iranian rials random\", \"1.00 Iraqi Dinar random\", \"1.00 Iraqi dinar random\", \"1.00 Iraqi dinars random\", \"1.00 Irish Pound random\", \"1.00 Irish pound random\", \"1.00 Irish pounds random\", \"1.00 Israeli Pound random\", \"1.00 Israeli new shekel random\", \"1.00 Israeli pound random\", \"1.00 Israeli pounds random\", \"1.00 Italian Lira random\", \"1.00 Italian lira random\", \"1.00 Italian liras random\", \"1.00 Jamaican Dollar random\", \"1.00 Jamaican dollar random\", \"1.00 Jamaican dollars random\", \"1.00 Japanese Yen random\", \"1.00 Japanese yen random\", \"1.00 Jordanian Dinar random\", \"1.00 Jordanian dinar random\", \"1.00 Jordanian dinars random\", \"1.00 Kazakhstani Tenge random\", \"1.00 Kazakhstani tenge random\", \"1.00 Kazakhstani tenges random\", \"1.00 Kenyan Shilling random\", \"1.00 Kenyan shilling random\", \"1.00 Kenyan shillings random\", \"1.00 Kuwaiti Dinar random\", \"1.00 Kuwaiti dinar random\", \"1.00 Kuwaiti dinars random\", \"1.00 Kyrgystani Som random\", \"1.00 Kyrgystani som random\", \"1.00 Kyrgystani soms random\", \"1.00 Laotian Kip random\", \"1.00 Laotian kip random\", \"1.00 Laotian kips random\", \"1.00 Latvian Lats random\", \"1.00 Latvian Ruble random\", \"1.00 Latvian lats random\", \"1.00 Latvian lati random\", \"1.00 Latvian ruble random\", \"1.00 Latvian rubles random\", \"1.00 Lebanese Pound random\", \"1.00 Lebanese pound random\", \"1.00 Lebanese pounds random\", \"1.00 Lesotho Loti random\", \"1.00 Lesotho loti random\", \"1.00 Lesotho lotis random\", \"1.00 Liberian Dollar random\", \"1.00 Liberian dollar random\", \"1.00 Liberian dollars random\", \"1.00 Libyan Dinar random\", \"1.00 Libyan dinar random\", \"1.00 Libyan dinars random\", \"1.00 Lithuanian Litas random\", \"1.00 Lithuanian Talonas random\", \"1.00 Lithuanian litas random\", \"1.00 Lithuanian litai random\", \"1.00 Lithuanian talonas random\", \"1.00 Lithuanian talonases random\", \"1.00 Luxembourgian Convertible Franc random\", \"1.00 Luxembourg Financial Franc random\", \"1.00 Luxembourgian Franc random\", \"1.00 Luxembourgian convertible franc random\", \"1.00 Luxembourgian convertible francs random\", \"1.00 Luxembourg financial franc random\", \"1.00 Luxembourg financial francs random\", \"1.00 Luxembourgian franc random\", \"1.00 Luxembourgian francs random\", \"1.00 Macanese Pataca random\", \"1.00 Macanese pataca random\", \"1.00 Macanese patacas random\", \"1.00 Macedonian Denar random\", \"1.00 Macedonian denar random\", \"1.00 Macedonian denari random\", \"1.00 Malagasy Ariaries random\", \"1.00 Malagasy Ariary random\", \"1.00 Malagasy Ariary random\", \"1.00 Malagasy Franc random\", \"1.00 Malagasy franc random\", \"1.00 Malagasy francs random\", \"1.00 Malawian Kwacha random\", \"1.00 Malawian Kwacha random\", \"1.00 Malawian Kwachas random\", \"1.00 Malaysian Ringgit random\", \"1.00 Malaysian ringgit random\", \"1.00 Malaysian ringgits random\", \"1.00 Maldivian Rufiyaa random\", \"1.00 Maldivian rufiyaa random\", \"1.00 Maldivian rufiyaas random\", \"1.00 Malian Franc random\", \"1.00 Malian franc random\", \"1.00 Malian francs random\", \"1.00 Maltese Lira random\", \"1.00 Maltese Pound random\", \"1.00 Maltese lira random\", \"1.00 Maltese liras random\", \"1.00 Maltese pound random\", \"1.00 Maltese pounds random\", \"1.00 Mauritanian Ouguiya random\", \"1.00 Mauritanian ouguiya random\", \"1.00 Mauritanian ouguiyas random\", \"1.00 Mauritian Rupee random\", \"1.00 Mauritian rupee random\", \"1.00 Mauritian rupees random\", \"1.00 Mexican Peso random\", \"1.00 Mexican Silver Peso (1861\\\\u20131992) random\", \"1.00 Mexican Investment Unit random\", \"1.00 Mexican peso random\", \"1.00 Mexican pesos random\", \"1.00 Mexican silver peso (1861\\\\u20131992) random\", \"1.00 Mexican silver pesos (1861\\\\u20131992) random\", \"1.00 Mexican investment unit random\", \"1.00 Mexican investment units random\", \"1.00 Moldovan Leu random\", \"1.00 Moldovan leu random\", \"1.00 Moldovan lei random\", \"1.00 Mongolian Tugrik random\", \"1.00 Mongolian tugrik random\", \"1.00 Mongolian tugriks random\", \"1.00 Moroccan Dirham random\", \"1.00 Moroccan Franc random\", \"1.00 Moroccan dirham random\", \"1.00 Moroccan dirhams random\", \"1.00 Moroccan franc random\", \"1.00 Moroccan francs random\", \"1.00 Mozambican Escudo random\", \"1.00 Mozambican Metical random\", \"1.00 Mozambican escudo random\", \"1.00 Mozambican escudos random\", \"1.00 Mozambican metical random\", \"1.00 Mozambican meticals random\", \"1.00 Myanmar Kyat random\", \"1.00 Myanmar kyat random\", \"1.00 Myanmar kyats random\", \"1.00 Namibian Dollar random\", \"1.00 Namibian dollar random\", \"1.00 Namibian dollars random\", \"1.00 Nepalese Rupee random\", \"1.00 Nepalese rupee random\", \"1.00 Nepalese rupees random\", \"1.00 Netherlands Antillean Guilder random\", \"1.00 Netherlands Antillean guilder random\", \"1.00 Netherlands Antillean guilders random\", \"1.00 Dutch Guilder random\", \"1.00 Dutch guilder random\", \"1.00 Dutch guilders random\", \"1.00 Israeli New Shekel random\", \"1.00 Israeli new shekels random\", \"1.00 New Zealand Dollar random\", \"1.00 New Zealand dollar random\", \"1.00 New Zealand dollars random\", \"1.00 Nicaraguan C\\\\u00f3rdoba random\", \"1.00 Nicaraguan C\\\\u00f3rdoba (1988\\\\u20131991) random\", \"1.00 Nicaraguan c\\\\u00f3rdoba random\", \"1.00 Nicaraguan c\\\\u00f3rdoba random\", \"1.00 Nicaraguan c\\\\u00f3rdoba (1988\\\\u20131991) random\", \"1.00 Nicaraguan c\\\\u00f3rdobas (1988\\\\u20131991) random\", \"1.00 Nigerian Naira random\", \"1.00 Nigerian naira random\", \"1.00 Nigerian nairas random\", \"1.00 North Korean Won random\", \"1.00 North Korean won random\", \"1.00 North Korean won random\", \"1.00 Norwegian Krone random\", \"1.00 Norwegian krone random\", \"1.00 Norwegian kroner random\", \"1.00 Mozambican Metical (1980\\\\u20132006) random\", \"1.00 Mozambican metical (1980\\\\u20132006) random\", \"1.00 Mozambican meticals (1980\\\\u20132006) random\", \"1.00 Romanian Lei (1952\\\\u20132006) random\", \"1.00 Romanian Leu (1952\\\\u20132006) random\", \"1.00 Romanian leu (1952\\\\u20132006) random\", \"1.00 Serbian Dinar (2002\\\\u20132006) random\", \"1.00 Serbian dinar (2002\\\\u20132006) random\", \"1.00 Serbian dinars (2002\\\\u20132006) random\", \"1.00 Sudanese Dinar (1992\\\\u20132007) random\", \"1.00 Sudanese Pound (1957\\\\u20131998) random\", \"1.00 Sudanese dinar (1992\\\\u20132007) random\", \"1.00 Sudanese dinars (1992\\\\u20132007) random\", \"1.00 Sudanese pound (1957\\\\u20131998) random\", \"1.00 Sudanese pounds (1957\\\\u20131998) random\", \"1.00 Turkish Lira (1922\\\\u20132005) random\", \"1.00 Turkish Lira (1922\\\\u20132005) random\", \"1.00 Omani Rial random\", \"1.00 Omani rial random\", \"1.00 Omani rials random\", \"1.00 Pakistani Rupee random\", \"1.00 Pakistani rupee random\", \"1.00 Pakistani rupees random\", \"1.00 Palladium random\", \"1.00 Palladium random\", \"1.00 Panamanian Balboa random\", \"1.00 Panamanian balboa random\", \"1.00 Panamanian balboas random\", \"1.00 Papua New Guinean Kina random\", \"1.00 Papua New Guinean kina random\", \"1.00 Papua New Guinean kina random\", \"1.00 Paraguayan Guarani random\", \"1.00 Paraguayan guarani random\", \"1.00 Paraguayan guaranis random\", \"1.00 Peruvian Inti random\", \"1.00 Peruvian Sol random\", \"1.00 Peruvian Sol (1863\\\\u20131965) random\", \"1.00 Peruvian inti random\", \"1.00 Peruvian intis random\", \"1.00 Peruvian sol random\", \"1.00 Peruvian soles random\", \"1.00 Peruvian sol (1863\\\\u20131965) random\", \"1.00 Peruvian soles (1863\\\\u20131965) random\", \"1.00 Philippine Piso random\", \"1.00 Philippine piso random\", \"1.00 Philippine pisos random\", \"1.00 Platinum random\", \"1.00 Platinum random\", \"1.00 Polish Zloty (1950\\\\u20131995) random\", \"1.00 Polish Zloty random\", \"1.00 Polish zlotys random\", \"1.00 Polish zloty (PLZ) random\", \"1.00 Polish zloty random\", \"1.00 Polish zlotys (PLZ) random\", \"1.00 Portuguese Escudo random\", \"1.00 Portuguese Guinea Escudo random\", \"1.00 Portuguese Guinea escudo random\", \"1.00 Portuguese Guinea escudos random\", \"1.00 Portuguese escudo random\", \"1.00 Portuguese escudos random\", \"1.00 Qatari Rial random\", \"1.00 Qatari rial random\", \"1.00 Qatari rials random\", \"1.00 RINET Funds random\", \"1.00 RINET Funds random\", \"1.00 Rhodesian Dollar random\", \"1.00 Rhodesian dollar random\", \"1.00 Rhodesian dollars random\", \"1.00 Romanian Leu random\", \"1.00 Romanian lei random\", \"1.00 Romanian leu random\", \"1.00 Russian Ruble (1991\\\\u20131998) random\", \"1.00 Russian Ruble random\", \"1.00 Russian ruble (1991\\\\u20131998) random\", \"1.00 Russian ruble random\", \"1.00 Russian rubles (1991\\\\u20131998) random\", \"1.00 Russian rubles random\", \"1.00 Rwandan Franc random\", \"1.00 Rwandan franc random\", \"1.00 Rwandan francs random\", \"1.00 St. Helena Pound random\", \"1.00 St. Helena pound random\", \"1.00 St. Helena pounds random\", \"1.00 S\\\\u00e3o Tom\\\\u00e9 & Pr\\\\u00edncipe Dobra random\", \"1.00 S\\\\u00e3o Tom\\\\u00e9 & Pr\\\\u00edncipe dobra random\", \"1.00 S\\\\u00e3o Tom\\\\u00e9 & Pr\\\\u00edncipe dobras random\", \"1.00 Saudi Riyal random\", \"1.00 Saudi riyal random\", \"1.00 Saudi riyals random\", \"1.00 Serbian Dinar random\", \"1.00 Serbian dinar random\", \"1.00 Serbian dinars random\", \"1.00 Seychellois Rupee random\", \"1.00 Seychellois rupee random\", \"1.00 Seychellois rupees random\", \"1.00 Sierra Leonean Leone random\", \"1.00 Sierra Leonean leone random\", \"1.00 Sierra Leonean leones random\", \"1.00 Singapore Dollar random\", \"1.00 Singapore dollar random\", \"1.00 Singapore dollars random\", \"1.00 Slovak Koruna random\", \"1.00 Slovak koruna random\", \"1.00 Slovak korunas random\", \"1.00 Slovenian Tolar random\", \"1.00 Slovenian tolar random\", \"1.00 Slovenian tolars random\", \"1.00 Solomon Islands Dollar random\", \"1.00 Solomon Islands dollar random\", \"1.00 Solomon Islands dollars random\", \"1.00 Somali Shilling random\", \"1.00 Somali shilling random\", \"1.00 Somali shillings random\", \"1.00 South African Rand (financial) random\", \"1.00 South African Rand random\", \"1.00 South African rand (financial) random\", \"1.00 South African rand random\", \"1.00 South African rands (financial) random\", \"1.00 South African rand random\", \"1.00 South Korean Won random\", \"1.00 South Korean won random\", \"1.00 South Korean won random\", \"1.00 Soviet Rouble random\", \"1.00 Soviet rouble random\", \"1.00 Soviet roubles random\", \"1.00 Spanish Peseta (A account) random\", \"1.00 Spanish Peseta (convertible account) random\", \"1.00 Spanish Peseta random\", \"1.00 Spanish peseta (A account) random\", \"1.00 Spanish peseta (convertible account) random\", \"1.00 Spanish peseta random\", \"1.00 Spanish pesetas (A account) random\", \"1.00 Spanish pesetas (convertible account) random\", \"1.00 Spanish pesetas random\", \"1.00 Special Drawing Rights random\", \"1.00 Sri Lankan Rupee random\", \"1.00 Sri Lankan rupee random\", \"1.00 Sri Lankan rupees random\", \"1.00 Sudanese Pound random\", \"1.00 Sudanese pound random\", \"1.00 Sudanese pounds random\", \"1.00 Surinamese Dollar random\", \"1.00 Surinamese dollar random\", \"1.00 Surinamese dollars random\", \"1.00 Surinamese Guilder random\", \"1.00 Surinamese guilder random\", \"1.00 Surinamese guilders random\", \"1.00 Swazi Lilangeni random\", \"1.00 Swazi lilangeni random\", \"1.00 Swazi emalangeni random\", \"1.00 Swedish Krona random\", \"1.00 Swedish krona random\", \"1.00 Swedish kronor random\", \"1.00 Swiss Franc random\", \"1.00 Swiss franc random\", \"1.00 Swiss francs random\", \"1.00 Syrian Pound random\", \"1.00 Syrian pound random\", \"1.00 Syrian pounds random\", \"1.00 New Taiwan Dollar random\", \"1.00 New Taiwan dollar random\", \"1.00 New Taiwan dollars random\", \"1.00 Tajikistani Ruble random\", \"1.00 Tajikistani Somoni random\", \"1.00 Tajikistani ruble random\", \"1.00 Tajikistani rubles random\", \"1.00 Tajikistani somoni random\", \"1.00 Tajikistani somonis random\", \"1.00 Tanzanian Shilling random\", \"1.00 Tanzanian shilling random\", \"1.00 Tanzanian shillings random\", \"1.00 Testing Currency Code random\", \"1.00 Testing Currency Code random\", \"1.00 Thai Baht random\", \"1.00 Thai baht random\", \"1.00 Thai baht random\", \"1.00 Timorese Escudo random\", \"1.00 Timorese escudo random\", \"1.00 Timorese escudos random\", \"1.00 Trinidad & Tobago Dollar random\", \"1.00 Trinidad & Tobago dollar random\", \"1.00 Trinidad & Tobago dollars random\", \"1.00 Tunisian Dinar random\", \"1.00 Tunisian dinar random\", \"1.00 Tunisian dinars random\", \"1.00 Turkish Lira random\", \"1.00 Turkish Lira random\", \"1.00 Turkish lira random\", \"1.00 Turkmenistani Manat random\", \"1.00 Turkmenistani manat random\", \"1.00 Turkmenistani manat random\", \"1.00 US Dollar (Next day) random\", \"1.00 US Dollar (Same day) random\", \"1.00 US Dollar random\", \"1.00 US dollar (next day) random\", \"1.00 US dollar (same day) random\", \"1.00 US dollar random\", \"1.00 US dollars (next day) random\", \"1.00 US dollars (same day) random\", \"1.00 US dollars random\", \"1.00 Ugandan Shilling (1966\\\\u20131987) random\", \"1.00 Ugandan Shilling random\", \"1.00 Ugandan shilling (1966\\\\u20131987) random\", \"1.00 Ugandan shilling random\", \"1.00 Ugandan shillings (1966\\\\u20131987) random\", \"1.00 Ugandan shillings random\", \"1.00 Ukrainian Hryvnia random\", \"1.00 Ukrainian Karbovanets random\", \"1.00 Ukrainian hryvnia random\", \"1.00 Ukrainian hryvnias random\", \"1.00 Ukrainian karbovanets random\", \"1.00 Ukrainian karbovantsiv random\", \"1.00 Colombian Real Value Unit random\", \"1.00 United Arab Emirates Dirham random\", \"1.00 Unknown Currency random\", \"1.00 Uruguayan Peso (1975\\\\u20131993) random\", \"1.00 Uruguayan Peso random\", \"1.00 Uruguayan Peso (Indexed Units) random\", \"1.00 Uruguayan peso (1975\\\\u20131993) random\", \"1.00 Uruguayan peso (indexed units) random\", \"1.00 Uruguayan peso random\", \"1.00 Uruguayan pesos (1975\\\\u20131993) random\", \"1.00 Uruguayan pesos (indexed units) random\", \"1.00 Uzbekistani Som random\", \"1.00 Uzbekistani som random\", \"1.00 Uzbekistani som random\", \"1.00 Vanuatu Vatu random\", \"1.00 Vanuatu vatu random\", \"1.00 Vanuatu vatus random\", \"1.00 Venezuelan Bol\\\\u00edvar random\", \"1.00 Venezuelan Bol\\\\u00edvar (1871\\\\u20132008) random\", \"1.00 Venezuelan bol\\\\u00edvar random\", \"1.00 Venezuelan bol\\\\u00edvars random\", \"1.00 Venezuelan bol\\\\u00edvar (1871\\\\u20132008) random\", \"1.00 Venezuelan bol\\\\u00edvars (1871\\\\u20132008) random\", \"1.00 Vietnamese Dong random\", \"1.00 Vietnamese dong random\", \"1.00 Vietnamese dong random\", \"1.00 WIR Euro random\", \"1.00 WIR Franc random\", \"1.00 WIR euro random\", \"1.00 WIR euros random\", \"1.00 WIR franc random\", \"1.00 WIR francs random\", \"1.00 Samoan Tala random\", \"1.00 Samoan tala random\", \"1.00 Samoan tala random\", \"1.00 Yemeni Dinar random\", \"1.00 Yemeni Rial random\", \"1.00 Yemeni dinar random\", \"1.00 Yemeni dinars random\", \"1.00 Yemeni rial random\", \"1.00 Yemeni rials random\", \"1.00 Yugoslavian Convertible Dinar (1990\\\\u20131992) random\", \"1.00 Yugoslavian Hard Dinar (1966\\\\u20131990) random\", \"1.00 Yugoslavian New Dinar (1994\\\\u20132002) random\", \"1.00 Yugoslavian convertible dinar (1990\\\\u20131992) random\", \"1.00 Yugoslavian convertible dinars (1990\\\\u20131992) random\", \"1.00 Yugoslavian hard dinar (1966\\\\u20131990) random\", \"1.00 Yugoslavian hard dinars (1966\\\\u20131990) random\", \"1.00 Yugoslavian new dinar (1994\\\\u20132002) random\", \"1.00 Yugoslavian new dinars (1994\\\\u20132002) random\", \"1.00 Zairean New Zaire (1993\\\\u20131998) random\", \"1.00 Zairean Zaire (1971\\\\u20131993) random\", \"1.00 Zairean new zaire (1993\\\\u20131998) random\", \"1.00 Zairean new zaires (1993\\\\u20131998) random\", \"1.00 Zairean zaire (1971\\\\u20131993) random\", \"1.00 Zairean zaires (1971\\\\u20131993) random\", \"1.00 Zambian Kwacha random\", \"1.00 Zambian kwacha random\", \"1.00 Zambian kwachas random\", \"1.00 Zimbabwean Dollar (1980\\\\u20132008) random\", \"1.00 Zimbabwean dollar (1980\\\\u20132008) random\", \"1.00 Zimbabwean dollars (1980\\\\u20132008) random\", \"1.00 euro random\", \"1.00 euros random\", \"1.00 Turkish lira (1922\\\\u20132005) random\", \"1.00 special drawing rights random\", \"1.00 Colombian real value unit random\", \"1.00 Colombian real value units random\", \"1.00 unknown currency random\", }; const char* WRONG_DATA[] = { \/\/ Following are missing one last char in the currency name \"1.00 Nicaraguan Cordob\", \"1.00 Namibian Dolla\", \"1.00 Namibian dolla\", \"1.00 Nepalese Rupe\", \"1.00 Nepalese rupe\", \"1.00 Netherlands Antillean Guilde\", \"1.00 Netherlands Antillean guilde\", \"1.00 Dutch Guilde\", \"1.00 Dutch guilde\", \"1.00 Israeli New Sheqe\", \"1.00 New Zealand Dolla\", \"1.00 New Zealand dolla\", \"1.00 Nicaraguan cordob\", \"1.00 Nigerian Nair\", \"1.00 Nigerian nair\", \"1.00 North Korean Wo\", \"1.00 North Korean wo\", \"1.00 Norwegian Kron\", \"1.00 Norwegian kron\", \"1.00 US dolla\", \"1.00\", \"A1.00\", \"AD1.00\", \"AE1.00\", \"AF1.00\", \"AL1.00\", \"AM1.00\", \"AN1.00\", \"AO1.00\", \"AR1.00\", \"AT1.00\", \"AU1.00\", \"AW1.00\", \"AZ1.00\", \"Afghan Afghan1.00\", \"Afghan Afghani (1927\\\\u201320021.00\", \"Afl1.00\", \"Albanian Le1.00\", \"Algerian Dina1.00\", \"Andorran Peset1.00\", \"Angolan Kwanz1.00\", \"Angolan Kwanza (1977\\\\u201319901.00\", \"Angolan Readjusted Kwanza (1995\\\\u201319991.00\", \"Angolan New Kwanza (1990\\\\u201320001.00\", \"Argentine Austra1.00\", \"Argentine Pes1.00\", \"Argentine Peso (1983\\\\u201319851.00\", \"Armenian Dra1.00\", \"Aruban Flori1.00\", \"Australian Dolla1.00\", \"Austrian Schillin1.00\", \"Azerbaijani Mana1.00\", \"Azerbaijani Manat (1993\\\\u201320061.00\", \"B1.00\", \"BA1.00\", \"BB1.00\", \"BE1.00\", \"BG1.00\", \"BH1.00\", \"BI1.00\", \"BM1.00\", \"BN1.00\", \"BO1.00\", \"BR1.00\", \"BS1.00\", \"BT1.00\", \"BU1.00\", \"BW1.00\", \"BY1.00\", \"BZ1.00\", \"Bahamian Dolla1.00\", \"Bahraini Dina1.00\", \"Bangladeshi Tak1.00\", \"Barbadian Dolla1.00\", \"Bds1.00\", \"Belarusian Ruble (1994\\\\u201319991.00\", \"Belarusian Rubl1.00\", \"Belgian Fran1.00\", \"Belgian Franc (convertible1.00\", \"Belgian Franc (financial1.00\", \"Belize Dolla1.00\", \"Bermudan Dolla1.00\", \"Bhutanese Ngultru1.00\", \"Bolivian Mvdo1.00\", \"Bolivian Pes1.00\", \"Bolivian Bolivian1.00\", \"Bosnia-Herzegovina Convertible Mar1.00\", \"Bosnia-Herzegovina Dina1.00\", \"Botswanan Pul1.00\", \"Brazilian Cruzad1.00\", \"Brazilian Cruzado Nov1.00\", \"Brazilian Cruzeir1.00\", \"Brazilian Cruzeiro (1990\\\\u201319931.00\", \"Brazilian New Cruzeiro (1967\\\\u201319861.00\", \"Brazilian Rea1.00\", \"British Pound Sterlin1.00\", \"Brunei Dolla1.00\", \"Bulgarian Hard Le1.00\", \"Bulgarian Le1.00\", \"Burmese Kya1.00\", \"Burundian Fran1.00\", \"C1.00\", \"CA1.00\", \"CD1.00\", \"CFP Fran1.00\", \"CFP1.00\", \"CH1.00\", \"CL1.00\", \"CN1.00\", \"CO1.00\", \"CS1.00\", \"CU1.00\", \"CV1.00\", \"CY1.00\", \"CZ1.00\", \"Cambodian Rie1.00\", \"Canadian Dolla1.00\", \"Cape Verdean Escud1.00\", \"Cayman Islands Dolla1.00\", \"Chilean Pes1.00\", \"Chilean Unit of Accoun1.00\", \"Chinese Yua1.00\", \"Colombian Pes1.00\", \"Comoro Fran1.00\", \"Congolese Fran1.00\", \"Costa Rican Col\\\\u00f31.00\", \"Croatian Dina1.00\", \"Croatian Kun1.00\", \"Cuban Pes1.00\", \"Cypriot Poun1.00\", \"Czech Republic Korun1.00\", \"Czechoslovak Hard Korun1.00\", \"D1.00\", \"DD1.00\", \"DE1.00\", \"DJ1.00\", \"DK1.00\", \"DO1.00\", \"DZ1.00\", \"Danish Kron1.00\", \"German Mar1.00\", \"Djiboutian Fran1.00\", \"Dk1.00\", \"Dominican Pes1.00\", \"EC1.00\", \"EE1.00\", \"EG1.00\", \"EQ1.00\", \"ER1.00\", \"ES1.00\", \"ET1.00\", \"EU1.00\", \"East Caribbean Dolla1.00\", \"East German Ostmar1.00\", \"Ecuadorian Sucr1.00\", \"Ecuadorian Unit of Constant Valu1.00\", \"Egyptian Poun1.00\", \"Ekwel1.00\", \"Salvadoran Col\\\\u00f31.00\", \"Equatorial Guinean Ekwel1.00\", \"Eritrean Nakf1.00\", \"Es1.00\", \"Estonian Kroo1.00\", \"Ethiopian Bir1.00\", \"Eur1.00\", \"European Composite Uni1.00\", \"European Currency Uni1.00\", \"European Monetary Uni1.00\", \"European Unit of Account (XBC1.00\", \"European Unit of Account (XBD1.00\", \"F1.00\", \"FB1.00\", \"FI1.00\", \"FJ1.00\", \"FK1.00\", \"FR1.00\", \"Falkland Islands Poun1.00\", \"Fd1.00\", \"Fijian Dolla1.00\", \"Finnish Markk1.00\", \"Fr1.00\", \"French Fran1.00\", \"French Gold Fran1.00\", \"French UIC-Fran1.00\", \"G1.00\", \"GB1.00\", \"GE1.00\", \"GH1.00\", \"GI1.00\", \"GM1.00\", \"GN1.00\", \"GQ1.00\", \"GR1.00\", \"GT1.00\", \"GW1.00\", \"GY1.00\", \"Gambian Dalas1.00\", \"Georgian Kupon Lari1.00\", \"Georgian Lar1.00\", \"Ghanaian Ced1.00\", \"Ghanaian Cedi (1979\\\\u201320071.00\", \"Gibraltar Poun1.00\", \"Gol1.00\", \"Greek Drachm1.00\", \"Guatemalan Quetza1.00\", \"Guinean Fran1.00\", \"Guinean Syl1.00\", \"Guinea-Bissau Pes1.00\", \"Guyanaese Dolla1.00\", \"HK1.00\", \"HN1.00\", \"HR1.00\", \"HT1.00\", \"HU1.00\", \"Haitian Gourd1.00\", \"Honduran Lempir1.00\", \"Hong Kong Dolla1.00\", \"Hungarian Forin1.00\", \"I1.00\", \"IE1.00\", \"IL1.00\", \"IN1.00\", \"IQ1.00\", \"IR1.00\", \"IS1.00\", \"IT1.00\", \"Icelandic Kron1.00\", \"Indian Rupe1.00\", \"Indonesian Rupia1.00\", \"Iranian Ria1.00\", \"Iraqi Dina1.00\", \"Irish Poun1.00\", \"Israeli Poun1.00\", \"Italian Lir1.00\", \"J1.00\", \"JM1.00\", \"JO1.00\", \"JP1.00\", \"Jamaican Dolla1.00\", \"Japanese Ye1.00\", \"Jordanian Dina1.00\", \"K S1.00\", \"K1.00\", \"KE1.00\", \"KG1.00\", \"KH1.00\", \"KP1.00\", \"KR1.00\", \"KW1.00\", \"KY1.00\", \"KZ1.00\", \"Kazakhstani Teng1.00\", \"Kenyan Shillin1.00\", \"Kuwaiti Dina1.00\", \"Kyrgystani So1.00\", \"LA1.00\", \"LB1.00\", \"LK1.00\", \"LR1.00\", \"LT1.00\", \"LU1.00\", \"LV1.00\", \"LY1.00\", \"Laotian Ki1.00\", \"Latvian Lat1.00\", \"Latvian Rubl1.00\", \"Lebanese Poun1.00\", \"Lesotho Lot1.00\", \"Liberian Dolla1.00\", \"Libyan Dina1.00\", \"Lithuanian Lit1.00\", \"Lithuanian Talona1.00\", \"Luxembourgian Convertible Fran1.00\", \"Luxembourg Financial Fran1.00\", \"Luxembourgian Fran1.00\", \"MA1.00\", \"MD1.00\", \"MDe1.00\", \"MEX1.00\", \"MG1.00\", \"ML1.00\", \"MM1.00\", \"MN1.00\", \"MO1.00\", \"MR1.00\", \"MT1.00\", \"MU1.00\", \"MV1.00\", \"MW1.00\", \"MX1.00\", \"MY1.00\", \"MZ1.00\", \"Macanese Patac1.00\", \"Macedonian Dena1.00\", \"Malagasy Ariar1.00\", \"Malagasy Fran1.00\", \"Malawian Kwach1.00\", \"Malaysian Ringgi1.00\", \"Maldivian Rufiya1.00\", \"Malian Fran1.00\", \"Malot1.00\", \"Maltese Lir1.00\", \"Maltese Poun1.00\", \"Mauritanian Ouguiy1.00\", \"Mauritian Rupe1.00\", \"Mexican Pes1.00\", \"Mexican Silver Peso (1861\\\\u201319921.00\", \"Mexican Investment Uni1.00\", \"Moldovan Le1.00\", \"Mongolian Tugri1.00\", \"Moroccan Dirha1.00\", \"Moroccan Fran1.00\", \"Mozambican Escud1.00\", \"Mozambican Metica1.00\", \"Myanmar Kya1.00\", \"N1.00\", \"NA1.00\", \"NAf1.00\", \"NG1.00\", \"NI1.00\", \"NK1.00\", \"NL1.00\", \"NO1.00\", \"NP1.00\", \"NT1.00\", \"Namibian Dolla1.00\", \"Nepalese Rupe1.00\", \"Netherlands Antillean Guilde1.00\", \"Dutch Guilde1.00\", \"Israeli New Sheqe1.00\", \"New Zealand Dolla1.00\", \"Nicaraguan C\\\\u00f3rdoba (1988\\\\u201319911.00\", \"Nicaraguan C\\\\u00f3rdob1.00\", \"Nigerian Nair1.00\", \"North Korean Wo1.00\", \"Norwegian Kron1.00\", \"Nr1.00\", \"OM1.00\", \"Old Mozambican Metica1.00\", \"Romanian Leu (1952\\\\u201320061.00\", \"Serbian Dinar (2002\\\\u201320061.00\", \"Sudanese Dinar (1992\\\\u201320071.00\", \"Sudanese Pound (1957\\\\u201319981.00\", \"Turkish Lira (1922\\\\u201320051.00\", \"Omani Ria1.00\", \"PA1.00\", \"PE1.00\", \"PG1.00\", \"PH1.00\", \"PK1.00\", \"PL1.00\", \"PT1.00\", \"PY1.00\", \"Pakistani Rupe1.00\", \"Palladiu1.00\", \"Panamanian Balbo1.00\", \"Papua New Guinean Kin1.00\", \"Paraguayan Guaran1.00\", \"Peruvian Int1.00\", \"Peruvian Sol (1863\\\\u201319651.00\", \"Peruvian Sol Nuev1.00\", \"Philippine Pes1.00\", \"Platinu1.00\", \"Polish Zlot1.00\", \"Polish Zloty (1950\\\\u201319951.00\", \"Portuguese Escud1.00\", \"Portuguese Guinea Escud1.00\", \"Pr1.00\", \"QA1.00\", \"Qatari Ria1.00\", \"RD1.00\", \"RH1.00\", \"RINET Fund1.00\", \"RS1.00\", \"RU1.00\", \"RW1.00\", \"Rb1.00\", \"Rhodesian Dolla1.00\", \"Romanian Le1.00\", \"Russian Rubl1.00\", \"Russian Ruble (1991\\\\u201319981.00\", \"Rwandan Fran1.00\", \"S1.00\", \"SA1.00\", \"SB1.00\", \"SC1.00\", \"SD1.00\", \"SE1.00\", \"SG1.00\", \"SH1.00\", \"SI1.00\", \"SK1.00\", \"SL R1.00\", \"SL1.00\", \"SO1.00\", \"ST1.00\", \"SU1.00\", \"SV1.00\", \"SY1.00\", \"SZ1.00\", \"St. Helena Poun1.00\", \"S\\\\u00e3o Tom\\\\u00e9 & Pr\\\\u00edncipe Dobr1.00\", \"Saudi Riya1.00\", \"Serbian Dina1.00\", \"Seychellois Rupe1.00\", \"Sh1.00\", \"Sierra Leonean Leon1.00\", \"Silve1.00\", \"Singapore Dolla1.00\", \"Slovak Korun1.00\", \"Slovenian Tola1.00\", \"Solomon Islands Dolla1.00\", \"Somali Shillin1.00\", \"South African Ran1.00\", \"South African Rand (financial1.00\", \"South Korean Wo1.00\", \"Soviet Roubl1.00\", \"Spanish Peset1.00\", \"Spanish Peseta (A account1.00\", \"Spanish Peseta (convertible account1.00\", \"Special Drawing Right1.00\", \"Sri Lankan Rupe1.00\", \"Sudanese Poun1.00\", \"Surinamese Dolla1.00\", \"Surinamese Guilde1.00\", \"Swazi Lilangen1.00\", \"Swedish Kron1.00\", \"Swiss Fran1.00\", \"Syrian Poun1.00\", \"T S1.00\", \"TH1.00\", \"TJ1.00\", \"TM1.00\", \"TN1.00\", \"TO1.00\", \"TP1.00\", \"TR1.00\", \"TT1.00\", \"TW1.00\", \"TZ1.00\", \"New Taiwan Dolla1.00\", \"Tajikistani Rubl1.00\", \"Tajikistani Somon1.00\", \"Tanzanian Shillin1.00\", \"Testing Currency Cod1.00\", \"Thai Bah1.00\", \"Timorese Escud1.00\", \"Tongan Pa\\\\u20bbang1.00\", \"Trinidad & Tobago Dolla1.00\", \"Tunisian Dina1.00\", \"Turkish Lir1.00\", \"Turkmenistani Mana1.00\", \"U S1.00\", \"U1.00\", \"UA1.00\", \"UG1.00\", \"US Dolla1.00\", \"US Dollar (Next day1.00\", \"US Dollar (Same day1.00\", \"US1.00\", \"UY1.00\", \"UZ1.00\", \"Ugandan Shillin1.00\", \"Ugandan Shilling (1966\\\\u201319871.00\", \"Ukrainian Hryvni1.00\", \"Ukrainian Karbovanet1.00\", \"Colombian Real Value Uni1.00\", \"United Arab Emirates Dirha1.00\", \"Unknown Currenc1.00\", \"Ur1.00\", \"Uruguay Peso (1975\\\\u201319931.00\", \"Uruguay Peso Uruguay1.00\", \"Uruguay Peso (Indexed Units1.00\", \"Uzbekistani So1.00\", \"V1.00\", \"VE1.00\", \"VN1.00\", \"VU1.00\", \"Vanuatu Vat1.00\", \"Venezuelan Bol\\\\u00edva1.00\", \"Venezuelan Bol\\\\u00edvar Fuert1.00\", \"Vietnamese Don1.00\", \"West African CFA Fran1.00\", \"Central African CFA Fran1.00\", \"WIR Eur1.00\", \"WIR Fran1.00\", \"WS1.00\", \"Samoa Tal1.00\", \"XA1.00\", \"XB1.00\", \"XC1.00\", \"XD1.00\", \"XE1.00\", \"XF1.00\", \"XO1.00\", \"XP1.00\", \"XR1.00\", \"XT1.00\", \"XX1.00\", \"YD1.00\", \"YE1.00\", \"YU1.00\", \"Yemeni Dina1.00\", \"Yemeni Ria1.00\", \"Yugoslavian Convertible Dina1.00\", \"Yugoslavian Hard Dinar (1966\\\\u201319901.00\", \"Yugoslavian New Dina1.00\", \"Z1.00\", \"ZA1.00\", \"ZM1.00\", \"ZR1.00\", \"ZW1.00\", \"Zairean New Zaire (1993\\\\u201319981.00\", \"Zairean Zair1.00\", \"Zambian Kwach1.00\", \"Zimbabwean Dollar (1980\\\\u201320081.00\", \"dra1.00\", \"lar1.00\", \"le1.00\", \"man1.00\", \"so1.00\", }; Locale locale(\"en_US\"); for (uint32_t i=0; i numFmt(NumberFormat::createInstance(locale, UNUM_CURRENCY, status), status); if (!assertSuccess(\"\", status, true, __FILE__, __LINE__)) { return; } \/\/ NOTE: ICU 62 requires that the currency format match the pattern in strict mode. numFmt->setLenient(TRUE); ParsePosition parsePos; LocalPointer currAmt(numFmt->parseCurrency(formatted, parsePos)); if (parsePos.getIndex() > 0) { double doubleVal = currAmt->getNumber().getDouble(status); if ( doubleVal != 1.0 ) { errln(\"Parsed as currency value other than 1.0: \" + formatted + \" -> \" + doubleVal); } } else { errln(\"Failed to parse as currency: \" + formatted); } } for (uint32_t i=0; i currAmt(numFmt->parseCurrency(formatted, parsePos)); if (parsePos.getIndex() > 0) { double doubleVal = currAmt->getNumber().getDouble(status); errln(\"Parsed as currency, should not have: \" + formatted + \" -> \" + doubleVal); } } else { dataerrln(\"Unable to create NumberFormat. - %s\", u_errorName(status)); delete numFmt; break; } delete numFmt; } }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":9479,"input":"yyparse (void *yyscanner, YR_COMPILER* compiler) { \/* The lookahead symbol. *\/ int yychar; \/* The semantic value of the lookahead symbol. *\/ \/* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. *\/ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); \/* Number of syntax errors so far. *\/ int yynerrs; int yystate; \/* Number of tokens to shift before error messages enabled. *\/ int yyerrstatus; \/* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. *\/ \/* The state stack. *\/ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; \/* The semantic value stack. *\/ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; \/* Lookahead token as an internal (translated) token number. *\/ int yytoken = 0; \/* The variables used to return semantic value and location from the action routines. *\/ YYSTYPE yyval; #if YYERROR_VERBOSE \/* Buffer for error messages, and its allocated size. *\/ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) \/* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. *\/ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, \"Starting parse\\n\")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; \/* Cause a token to be read. *\/ goto yysetstate; \/*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*\/ yynewstate: \/* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. *\/ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { \/* Get the current used size of the three stacks, in elements. *\/ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { \/* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. *\/ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; \/* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. *\/ yyoverflow (YY_(\"memory exhausted\"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else \/* no yyoverflow *\/ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else \/* Extend the stack our own way. *\/ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif \/* no yyoverflow *\/ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, \"Stack size increased to %lu\\n\", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, \"Entering state %d\\n\", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; \/*-----------. | yybackup. | `-----------*\/ yybackup: \/* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. *\/ \/* First try to decide what to do without reference to lookahead token. *\/ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; \/* Not known => get a lookahead token if don't already have one. *\/ \/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. *\/ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, \"Reading a token: \")); yychar = yylex (&yylval, yyscanner, compiler); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, \"Now at end of input.\\n\")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT (\"Next token is\", yytoken, &yylval, &yylloc); } \/* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. *\/ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } \/* Count tokens shifted since error; after three, turn off error status. *\/ if (yyerrstatus) yyerrstatus--; \/* Shift the lookahead token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yytoken, &yylval, &yylloc); \/* Discard the shifted token. *\/ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; \/*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*\/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; \/*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*\/ yyreduce: \/* yyn is the number of a rule to reduce with. *\/ yylen = yyr2[yyn]; \/* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. *\/ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 8: #line 230 \"grammar.y\" \/* yacc.c:1646 *\/ { int result = yr_parser_reduce_import(yyscanner, (yyvsp[0].sized_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF(result != ERROR_SUCCESS); } #line 1661 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 9: #line 242 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_RULE* rule = yr_parser_reduce_rule_declaration_phase_1( yyscanner, (int32_t) (yyvsp[-2].integer), (yyvsp[0].c_string)); ERROR_IF(rule == NULL); (yyval.rule) = rule; } #line 1674 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 10: #line 251 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_RULE* rule = (yyvsp[-4].rule); \/\/ rule created in phase 1 rule->tags = (yyvsp[-3].c_string); rule->metas = (yyvsp[-1].meta); rule->strings = (yyvsp[0].string); } #line 1686 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 11: #line 259 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_RULE* rule = (yyvsp[-7].rule); \/\/ rule created in phase 1 compiler->last_result = yr_parser_reduce_rule_declaration_phase_2( yyscanner, rule); yr_free((yyvsp[-8].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1701 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 12: #line 274 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = NULL; } #line 1709 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 13: #line 278 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_META null_meta; memset(&null_meta, 0xFF, sizeof(YR_META)); null_meta.type = META_TYPE_NULL; compiler->last_result = yr_arena_write_data( compiler->metas_arena, &null_meta, sizeof(YR_META), NULL); (yyval.meta) = (yyvsp[0].meta); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1736 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 14: #line 305 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = NULL; } #line 1744 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 15: #line 309 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_STRING null_string; memset(&null_string, 0xFF, sizeof(YR_STRING)); null_string.g_flags = STRING_GFLAGS_NULL; compiler->last_result = yr_arena_write_data( compiler->strings_arena, &null_string, sizeof(YR_STRING), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.string) = (yyvsp[0].string); } #line 1771 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 17: #line 340 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = 0; } #line 1777 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 18: #line 341 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 1783 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 19: #line 346 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = RULE_GFLAGS_PRIVATE; } #line 1789 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 20: #line 347 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = RULE_GFLAGS_GLOBAL; } #line 1795 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 21: #line 353 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = NULL; } #line 1803 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 22: #line 357 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, \"\", NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[0].c_string); } #line 1821 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 23: #line 375 \"grammar.y\" \/* yacc.c:1646 *\/ { char* identifier; compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), &identifier); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = identifier; } #line 1838 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 24: #line 388 \"grammar.y\" \/* yacc.c:1646 *\/ { char* tag_name = (yyvsp[-1].c_string); size_t tag_length = tag_name != NULL ? strlen(tag_name) : 0; while (tag_length > 0) { if (strcmp(tag_name, (yyvsp[0].c_string)) == 0) { yr_compiler_set_error_extra_info(compiler, tag_name); compiler->last_result = ERROR_DUPLICATED_TAG_IDENTIFIER; break; } tag_name = (char*) yr_arena_next_address( yyget_extra(yyscanner)->sz_arena, tag_name, tag_length + 1); tag_length = tag_name != NULL ? strlen(tag_name) : 0; } if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), NULL); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-1].c_string); } #line 1874 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 25: #line 424 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = (yyvsp[0].meta); } #line 1880 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 26: #line 425 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = (yyvsp[-1].meta); } #line 1886 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 27: #line 431 \"grammar.y\" \/* yacc.c:1646 *\/ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_STRING, (yyvsp[-2].c_string), sized_string->c_string, 0); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.meta) == NULL); } #line 1906 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 28: #line 447 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-2].c_string), NULL, (yyvsp[0].integer)); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1923 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 29: #line 460 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-3].c_string), NULL, -(yyvsp[0].integer)); yr_free((yyvsp[-3].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1940 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 30: #line 473 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, TRUE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1957 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 31: #line 486 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, FALSE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1974 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 32: #line 502 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = (yyvsp[0].string); } #line 1980 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 33: #line 503 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = (yyvsp[-1].string); } #line 1986 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 34: #line 509 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->error_line = yyget_lineno(yyscanner); } #line 1994 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 35: #line 513 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer), (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2009 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 36: #line 524 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->error_line = yyget_lineno(yyscanner); } #line 2017 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 37: #line 528 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer) | STRING_GFLAGS_REGEXP, (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2033 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 38: #line 540 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, STRING_GFLAGS_HEXADECIMAL, (yyvsp[-2].c_string), (yyvsp[0].sized_string)); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.string) == NULL); } #line 2047 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 39: #line 553 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = 0; } #line 2053 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 40: #line 554 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 2059 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 41: #line 559 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_WIDE; } #line 2065 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 42: #line 560 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_ASCII; } #line 2071 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 43: #line 561 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_NO_CASE; } #line 2077 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 44: #line 562 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_FULL_WORD; } #line 2083 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 45: #line 568 \"grammar.y\" \/* yacc.c:1646 *\/ { int var_index = yr_parser_lookup_loop_variable(yyscanner, (yyvsp[0].c_string)); if (var_index >= 0) { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, LOOP_LOCAL_VARS * var_index, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = compiler->loop_identifier[var_index]; } else { YR_OBJECT* object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), NULL); if (object == NULL) { char* ns = compiler->current_namespace->name; object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), ns); } if (object != NULL) { char* id; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &id); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_LOAD, id, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = object; (yyval.expression).identifier = object->identifier; } else { YR_RULE* rule = (YR_RULE*) yr_hash_table_lookup( compiler->rules_table, (yyvsp[0].c_string), compiler->current_namespace->name); if (rule != NULL) { compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH_RULE, rule, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = rule->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_UNDEFINED_IDENTIFIER; } } } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2172 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 46: #line 653 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_OBJECT* field = NULL; if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-2].expression).value.object->type == OBJECT_TYPE_STRUCTURE) { field = yr_object_lookup_field((yyvsp[-2].expression).value.object, (yyvsp[0].c_string)); if (field != NULL) { char* ident; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &ident); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_FIELD, ident, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = field; (yyval.expression).identifier = field->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_INVALID_FIELD_NAME; } } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-2].expression).identifier); compiler->last_result = ERROR_NOT_A_STRUCTURE; } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2222 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 47: #line 699 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_OBJECT_ARRAY* array; YR_OBJECT_DICTIONARY* dict; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_ARRAY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"array indexes must be of integer type\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_INDEX_ARRAY, NULL); array = (YR_OBJECT_ARRAY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = array->prototype_item; (yyval.expression).identifier = array->identifier; } else if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_DICTIONARY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_STRING) { yr_compiler_set_error_extra_info( compiler, \"dictionary keys must be of string type\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_LOOKUP_DICT, NULL); dict = (YR_OBJECT_DICTIONARY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = dict->prototype_item; (yyval.expression).identifier = dict->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_INDEXABLE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2283 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 48: #line 757 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_OBJECT_FUNCTION* function; char* args_fmt; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_FUNCTION) { compiler->last_result = yr_parser_check_types( compiler, (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object, (yyvsp[-1].c_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[-1].c_string), &args_fmt); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_CALL, args_fmt, NULL, NULL); function = (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = function->return_obj; (yyval.expression).identifier = function->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_A_FUNCTION; } yr_free((yyvsp[-1].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2328 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 49: #line 801 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = yr_strdup(\"\"); } #line 2334 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 50: #line 802 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = (yyvsp[0].c_string); } #line 2340 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 51: #line 807 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = (char*) yr_malloc(MAX_FUNCTION_ARGS + 1); switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcpy((yyval.c_string), \"i\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcpy((yyval.c_string), \"f\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcpy((yyval.c_string), \"b\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcpy((yyval.c_string), \"s\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcpy((yyval.c_string), \"r\", MAX_FUNCTION_ARGS); break; } ERROR_IF((yyval.c_string) == NULL); } #line 2369 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 52: #line 832 \"grammar.y\" \/* yacc.c:1646 *\/ { if (strlen((yyvsp[-2].c_string)) == MAX_FUNCTION_ARGS) { compiler->last_result = ERROR_TOO_MANY_ARGUMENTS; } else { switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcat((yyvsp[-2].c_string), \"i\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcat((yyvsp[-2].c_string), \"f\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcat((yyvsp[-2].c_string), \"b\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcat((yyvsp[-2].c_string), \"s\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcat((yyvsp[-2].c_string), \"r\", MAX_FUNCTION_ARGS); break; } } ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-2].c_string); } #line 2405 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 53: #line 868 \"grammar.y\" \/* yacc.c:1646 *\/ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); RE* re; RE_ERROR error; int re_flags = 0; if (sized_string->flags & SIZED_STRING_FLAGS_NO_CASE) re_flags |= RE_FLAGS_NO_CASE; if (sized_string->flags & SIZED_STRING_FLAGS_DOT_ALL) re_flags |= RE_FLAGS_DOT_ALL; compiler->last_result = yr_re_compile( sized_string->c_string, re_flags, compiler->re_code_arena, &re, &error); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_INVALID_REGULAR_EXPRESSION) yr_compiler_set_error_extra_info(compiler, error.message); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, re->root_node->forward_code, NULL, NULL); yr_re_destroy(re); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_REGEXP; } #line 2451 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 54: #line 914 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_STRING) { if ((yyvsp[0].expression).value.sized_string != NULL) { yywarning(yyscanner, \"Using literal string \\\"%s\\\" in a boolean operation.\", (yyvsp[0].expression).value.sized_string->c_string); } compiler->last_result = yr_parser_emit( yyscanner, OP_STR_TO_BOOL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2474 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 55: #line 936 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2487 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 56: #line 945 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 0, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2500 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 57: #line 954 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, \"matches\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_REGEXP, \"matches\"); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit( yyscanner, OP_MATCHES, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2519 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 58: #line 969 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, \"contains\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_STRING, \"contains\"); compiler->last_result = yr_parser_emit( yyscanner, OP_CONTAINS, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2535 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 59: #line 981 \"grammar.y\" \/* yacc.c:1646 *\/ { int result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_FOUND, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2553 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 60: #line 995 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"at\"); compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_AT, (yyvsp[0].expression).value.integer); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2570 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 61: #line 1008 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_IN, UNDEFINED); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result!= ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2585 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 62: #line 1019 \"grammar.y\" \/* yacc.c:1646 *\/ { if (compiler->loop_depth > 0) { compiler->loop_depth--; compiler->loop_identifier[compiler->loop_depth] = NULL; } } #line 2597 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 63: #line 1027 \"grammar.y\" \/* yacc.c:1646 *\/ { int var_index; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \\ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; ERROR_IF(compiler->last_result != ERROR_SUCCESS); var_index = yr_parser_lookup_loop_variable( yyscanner, (yyvsp[-1].c_string)); if (var_index >= 0) { yr_compiler_set_error_extra_info( compiler, (yyvsp[-1].c_string)); compiler->last_result = \\ ERROR_DUPLICATED_LOOP_IDENTIFIER; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2631 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 64: #line 1057 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-1].integer) == INTEGER_SET_ENUMERATION) { yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); } else \/\/ INTEGER_SET_RANGE { yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset + 3, &addr, NULL); yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, NULL, NULL); } compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = (yyvsp[-4].c_string); compiler->loop_depth++; } #line 2670 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 65: #line 1092 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset; compiler->loop_depth--; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-5].integer) == INTEGER_SET_ENUMERATION) { yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); } else \/\/ INTEGER_SET_RANGE { yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 3, NULL, NULL); yr_parser_emit_with_arg_reloc( yyscanner, OP_JLE, compiler->loop_address[compiler->loop_depth], NULL, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); } yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); compiler->loop_identifier[compiler->loop_depth] = NULL; yr_free((yyvsp[-8].c_string)); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2753 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 66: #line 1171 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \\ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; if (compiler->loop_for_of_mem_offset != -1) compiler->last_result = \\ ERROR_NESTED_FOR_OF_LOOP; ERROR_IF(compiler->last_result != ERROR_SUCCESS); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); compiler->loop_for_of_mem_offset = mem_offset; compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = NULL; compiler->loop_depth++; } #line 2787 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 67: #line 1201 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset; compiler->loop_depth--; compiler->loop_for_of_mem_offset = -1; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2840 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 68: #line 1250 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit(yyscanner, OP_OF, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2850 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 69: #line 1256 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit(yyscanner, OP_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2860 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 70: #line 1262 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JFALSE, 0, \/\/ still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2890 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 71: #line 1288 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; uint8_t* and_addr; compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_AND, &and_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = compiler->fixup_stack_head; *(void**)(fixup->address) = (void*)(and_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2930 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 72: #line 1324 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JTRUE, 0, \/\/ still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2959 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 73: #line 1349 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; uint8_t* or_addr; compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_OR, &or_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = compiler->fixup_stack_head; *(void**)(fixup->address) = (void*)(or_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2999 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 74: #line 1385 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"<\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3012 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 75: #line 1394 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \">\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3025 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 76: #line 1403 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"<=\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3038 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 77: #line 1412 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \">=\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3051 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 78: #line 1421 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"==\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3064 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 79: #line 1430 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"!=\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3077 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 80: #line 1439 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[0].expression); } #line 3085 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 81: #line 1443 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[-1].expression); } #line 3093 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 82: #line 1450 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = INTEGER_SET_ENUMERATION; } #line 3099 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 83: #line 1451 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = INTEGER_SET_RANGE; } #line 3105 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 84: #line 1457 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[-3].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for range's lower bound\"); compiler->last_result = ERROR_WRONG_TYPE; } if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for range's upper bound\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3127 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 85: #line 1479 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for enumeration item\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3143 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 86: #line 1491 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for enumeration item\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3158 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 87: #line 1506 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3167 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 89: #line 1512 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); yr_parser_emit_pushes_for_strings(yyscanner, \"$*\"); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3178 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 92: #line 1529 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3189 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 93: #line 1536 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3200 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 95: #line 1548 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3208 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 96: #line 1552 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL); } #line 3216 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 97: #line 1560 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[-1].expression); } #line 3224 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 98: #line 1564 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit( yyscanner, OP_FILESIZE, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3238 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 99: #line 1574 \"grammar.y\" \/* yacc.c:1646 *\/ { yywarning(yyscanner, \"Using deprecated \\\"entrypoint\\\" keyword. Use the \\\"entry_point\\\" \" \"function from PE module instead.\"); compiler->last_result = yr_parser_emit( yyscanner, OP_ENTRYPOINT, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3256 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 100: #line 1588 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-1].expression), EXPRESSION_TYPE_INTEGER, \"intXXXX or uintXXXX\"); compiler->last_result = yr_parser_emit( yyscanner, (uint8_t) (OP_READ_INT + (yyvsp[-3].integer)), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3276 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 101: #line 1604 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, (yyvsp[0].integer), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = (yyvsp[0].integer); } #line 3290 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 102: #line 1614 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg_double( yyscanner, OP_PUSH, (yyvsp[0].double_), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } #line 3303 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 103: #line 1623 \"grammar.y\" \/* yacc.c:1646 *\/ { SIZED_STRING* sized_string; compiler->last_result = yr_arena_write_data( compiler->sz_arena, (yyvsp[0].sized_string), (yyvsp[0].sized_string)->length + sizeof(SIZED_STRING), (void**) &sized_string); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, sized_string, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = sized_string; } #line 3332 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 104: #line 1648 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_COUNT, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3348 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 105: #line 1660 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3364 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 106: #line 1672 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3384 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 107: #line 1688 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3400 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 108: #line 1700 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3420 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 109: #line 1716 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) \/\/ loop identifier { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_BOOLEAN) \/\/ rule identifier { (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_OBJECT) { compiler->last_result = yr_parser_emit( yyscanner, OP_OBJ_VALUE, NULL); switch((yyvsp[0].expression).value.object->type) { case OBJECT_TYPE_INTEGER: (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; break; case OBJECT_TYPE_FLOAT: (yyval.expression).type = EXPRESSION_TYPE_FLOAT; break; case OBJECT_TYPE_STRING: (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = NULL; break; default: yr_compiler_set_error_extra_info_fmt( compiler, \"wrong usage of identifier \\\"%s\\\"\", (yyvsp[0].expression).identifier); compiler->last_result = ERROR_WRONG_TYPE; } } else { assert(FALSE); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3469 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 110: #line 1761 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT, \"-\"); if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : -((yyvsp[0].expression).value.integer); compiler->last_result = yr_parser_emit(yyscanner, OP_INT_MINUS, NULL); } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_FLOAT) { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; compiler->last_result = yr_parser_emit(yyscanner, OP_DBL_MINUS, NULL); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3492 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 111: #line 1780 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"+\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(+, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3514 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 112: #line 1798 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"-\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(-, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3536 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 113: #line 1816 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"*\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(*, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3558 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 114: #line 1834 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"\\\\\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(\/, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3588 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 115: #line 1860 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"%\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"%\"); yr_parser_emit(yyscanner, OP_MOD, NULL); if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(%, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } #line 3610 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 116: #line 1878 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"^\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"^\"); yr_parser_emit(yyscanner, OP_BITWISE_XOR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(^, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3624 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 117: #line 1888 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"^\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"^\"); yr_parser_emit(yyscanner, OP_BITWISE_AND, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(&, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3638 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 118: #line 1898 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"|\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"|\"); yr_parser_emit(yyscanner, OP_BITWISE_OR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(|, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3652 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 119: #line 1908 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"~\"); yr_parser_emit(yyscanner, OP_BITWISE_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : ~((yyvsp[0].expression).value.integer); } #line 3666 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 120: #line 1918 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"<<\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"<<\"); yr_parser_emit(yyscanner, OP_SHL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(<<, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3680 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 121: #line 1928 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \">>\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \">>\"); yr_parser_emit(yyscanner, OP_SHR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(>>, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3694 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 122: #line 1938 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[0].expression); } #line 3702 \"grammar.c\" \/* yacc.c:1646 *\/ break; #line 3706 \"grammar.c\" \/* yacc.c:1646 *\/ default: break; } \/* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. *\/ YY_SYMBOL_PRINT (\"-> $$ =\", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; \/* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. *\/ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; \/*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*\/ yyerrlab: \/* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. *\/ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); \/* If not already recovering from an error, report this error. *\/ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (yyscanner, compiler, YY_(\"syntax error\")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \\ yyssp, yytoken) { char const *yymsgp = YY_(\"syntax error\"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yyscanner, compiler, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { \/* If just tried and failed to reuse lookahead token after an error, discard it. *\/ if (yychar <= YYEOF) { \/* Return failure if at end of input. *\/ if (yychar == YYEOF) YYABORT; } else { yydestruct (\"Error: discarding\", yytoken, &yylval, yyscanner, compiler); yychar = YYEMPTY; } } \/* Else will try to reuse lookahead token after shifting the error token. *\/ goto yyerrlab1; \/*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*\/ yyerrorlab: \/* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. *\/ if (\/*CONSTCOND*\/ 0) goto yyerrorlab; \/* Do not reclaim the symbols of the rule whose action triggered this YYERROR. *\/ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; \/*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*\/ yyerrlab1: yyerrstatus = 3; \/* Each real token shifted decrements this. *\/ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } \/* Pop the current state because it cannot handle the error token. *\/ if (yyssp == yyss) YYABORT; yydestruct (\"Error: popping\", yystos[yystate], yyvsp, yyscanner, compiler); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END \/* Shift the error token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; \/*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*\/ yyacceptlab: yyresult = 0; goto yyreturn; \/*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*\/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE \/*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*\/ yyexhaustedlab: yyerror (yyscanner, compiler, YY_(\"memory exhausted\")); yyresult = 2; \/* Fall through. *\/ #endif yyreturn: if (yychar != YYEMPTY) { \/* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. *\/ yytoken = YYTRANSLATE (yychar); yydestruct (\"Cleanup: discarding lookahead\", yytoken, &yylval, yyscanner, compiler); } \/* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. *\/ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct (\"Cleanup: popping\", yystos[*yyssp], yyvsp, yyscanner, compiler); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; }","output":{"is_vulnerable":"True","vulnerability_types":["Out-of-bounds Read"],"explanation":"libyara\/grammar.y in YARA 3.5.0 allows remote attackers to cause a denial of service (heap-based out-of-bounds read and application crash) via a crafted rule that is mishandled in the yara_yyparse function.","severity_level":"Medium","cwe":"CWE-125","cve":"CVE-2017-5923"}} -{"idx":207743,"input":"deliver_message(uschar *id, BOOL forced, BOOL give_up) { int i, rc; int final_yield = DELIVER_ATTEMPTED_NORMAL; time_t now = time(NULL); address_item *addr_last = NULL; uschar *filter_message = NULL; int process_recipients = RECIP_ACCEPT; open_db dbblock; open_db *dbm_file; extern int acl_where; uschar *info = queue_run_pid == (pid_t)0 ? string_sprintf(\"delivering %s\", id) : string_sprintf(\"delivering %s (queue run pid %d)\", id, queue_run_pid); \/* If the D_process_info bit is on, set_process_info() will output debugging information. If not, we want to show this initial information if D_deliver or D_queue_run is set or in verbose mode. *\/ set_process_info(\"%s\", info); if ( !(debug_selector & D_process_info) && (debug_selector & (D_deliver|D_queue_run|D_v)) ) debug_printf(\"%s\\n\", info); \/* Ensure that we catch any subprocesses that are created. Although Exim sets SIG_DFL as its initial default, some routes through the code end up here with it set to SIG_IGN - cases where a non-synchronous delivery process has been forked, but no re-exec has been done. We use sigaction rather than plain signal() on those OS where SA_NOCLDWAIT exists, because we want to be sure it is turned off. (There was a problem on AIX with this.) *\/ #ifdef SA_NOCLDWAIT { struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(SIGCHLD, &act, NULL); } #else signal(SIGCHLD, SIG_DFL); #endif \/* Make the forcing flag available for routers and transports, set up the global message id field, and initialize the count for returned files and the message size. This use of strcpy() is OK because the length id is checked when it is obtained from a command line (the -M or -q options), and otherwise it is known to be a valid message id. *\/ if (id != message_id) Ustrcpy(message_id, id); deliver_force = forced; return_count = 0; message_size = 0; \/* Initialize some flags *\/ update_spool = FALSE; remove_journal = TRUE; \/* Set a known context for any ACLs we call via expansions *\/ acl_where = ACL_WHERE_DELIVERY; \/* Reset the random number generator, so that if several delivery processes are started from a queue runner that has already used random numbers (for sorting), they don't all get the same sequence. *\/ random_seed = 0; \/* Open and lock the message's data file. Exim locks on this one because the header file may get replaced as it is re-written during the delivery process. Any failures cause messages to be written to the log, except for missing files while queue running - another process probably completed delivery. As part of opening the data file, message_subdir gets set. *\/ if ((deliver_datafile = spool_open_datafile(id)) < 0) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ \/* The value of message_size at this point has been set to the data length, plus one for the blank line that notionally precedes the data. *\/ \/* Now read the contents of the header file, which will set up the headers in store, and also the list of recipients and the tree of non-recipients and assorted flags. It updates message_size. If there is a reading or format error, give up; if the message has been around for sufficiently long, remove it. *\/ { uschar * spoolname = string_sprintf(\"%s-H\", id); if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK) { if (errno == ERRNO_SPOOLFORMAT) { struct stat statbuf; if (Ustat(spool_fname(US\"input\", message_subdir, spoolname, US\"\"), &statbuf) == 0) log_write(0, LOG_MAIN, \"Format error in spool file %s: \" \"size=\" OFF_T_FMT, spoolname, statbuf.st_size); else log_write(0, LOG_MAIN, \"Format error in spool file %s\", spoolname); } else log_write(0, LOG_MAIN, \"Error reading spool file %s: %s\", spoolname, strerror(errno)); \/* If we managed to read the envelope data, received_time contains the time the message was received. Otherwise, we can calculate it from the message id. *\/ if (rc != spool_read_hdrerror) { received_time.tv_sec = received_time.tv_usec = 0; \/*XXX subsec precision?*\/ for (i = 0; i < 6; i++) received_time.tv_sec = received_time.tv_sec * BASE_62 + tab62[id[i] - '0']; } \/* If we've had this malformed message too long, sling it. *\/ if (now - received_time.tv_sec > keep_malformed) { Uunlink(spool_fname(US\"msglog\", message_subdir, id, US\"\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-H\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-J\")); log_write(0, LOG_MAIN, \"Message removed because older than %s\", readconf_printtime(keep_malformed)); } (void)close(deliver_datafile); deliver_datafile = -1; return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* The spool header file has been read. Look to see if there is an existing journal file for this message. If there is, it means that a previous delivery attempt crashed (program or host) before it could update the spool header file. Read the list of delivered addresses from the journal and add them to the nonrecipients tree. Then update the spool file. We can leave the journal in existence, as it will get further successful deliveries added to it in this run, and it will be deleted if this function gets to its end successfully. Otherwise it might be needed again. *\/ { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); FILE * jread; if ( (journal_fd = Uopen(fname, O_RDWR|O_APPEND #ifdef O_CLOEXEC | O_CLOEXEC #endif #ifdef O_NOFOLLOW | O_NOFOLLOW #endif , SPOOL_MODE)) >= 0 && lseek(journal_fd, 0, SEEK_SET) == 0 && (jread = fdopen(journal_fd, \"rb\")) ) { while (Ufgets(big_buffer, big_buffer_size, jread)) { int n = Ustrlen(big_buffer); big_buffer[n-1] = 0; tree_add_nonrecipient(big_buffer); DEBUG(D_deliver) debug_printf(\"Previously delivered address %s taken from \" \"journal file\\n\", big_buffer); } rewind(jread); if ((journal_fd = dup(fileno(jread))) < 0) journal_fd = fileno(jread); else (void) fclose(jread); \/* Try to not leak the FILE resource *\/ \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } else if (errno != ENOENT) { log_write(0, LOG_MAIN|LOG_PANIC, \"attempt to open journal for reading gave: \" \"%s\", strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* A null recipients list indicates some kind of disaster. *\/ if (!recipients_list) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN, \"Spool error: no recipients for %s\", fname); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* Handle a message that is frozen. There are a number of different things that can happen, but in the default situation, unless forced, no delivery is attempted. *\/ if (deliver_freeze) { #ifdef SUPPORT_MOVE_FROZEN_MESSAGES \/* Moving to another directory removes the message from Exim's view. Other tools must be used to deal with it. Logging of this action happens in spool_move_message() and its subfunctions. *\/ if ( move_frozen_messages && spool_move_message(id, message_subdir, US\"\", US\"F\") ) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ #endif \/* For all frozen messages (bounces or not), timeout_frozen_after sets the maximum time to keep messages that are frozen. Thaw if we reach it, with a flag causing all recipients to be failed. The time is the age of the message, not the time since freezing. *\/ if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after) { log_write(0, LOG_MAIN, \"cancelled by timeout_frozen_after\"); process_recipients = RECIP_FAIL_TIMEOUT; } \/* For bounce messages (and others with no sender), thaw if the error message ignore timer is exceeded. The message will be discarded if this delivery fails. *\/ else if (!*sender_address && message_age >= ignore_bounce_errors_after) log_write(0, LOG_MAIN, \"Unfrozen by errmsg timer\"); \/* If this is a bounce message, or there's no auto thaw, or we haven't reached the auto thaw time yet, and this delivery is not forced by an admin user, do not attempt delivery of this message. Note that forced is set for continuing messages down the same channel, in order to skip load checking and ignore hold domains, but we don't want unfreezing in that case. *\/ else { if ( ( sender_address[0] == 0 || auto_thaw <= 0 || now <= deliver_frozen_at + auto_thaw ) && ( !forced || !deliver_force_thaw || !admin_user || continue_hostname ) ) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(L_skip_delivery, LOG_MAIN, \"Message is frozen\"); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* If delivery was forced (by an admin user), assume a manual thaw. Otherwise it's an auto thaw. *\/ if (forced) { deliver_manual_thaw = TRUE; log_write(0, LOG_MAIN, \"Unfrozen by forced delivery\"); } else log_write(0, LOG_MAIN, \"Unfrozen by auto-thaw\"); } \/* We get here if any of the rules for unfreezing have triggered. *\/ deliver_freeze = FALSE; update_spool = TRUE; } \/* Open the message log file if we are using them. This records details of deliveries, deferments, and failures for the benefit of the mail administrator. The log is not used by exim itself to track the progress of a message; that is done by rewriting the header spool file. *\/ if (message_logs) { uschar * fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); uschar * error; int fd; if ((fd = open_msglog_file(fname, SPOOL_MODE, &error)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't %s message log %s: %s\", error, fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Make a C stream out of it. *\/ if (!(message_log = fdopen(fd, \"a\"))) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't fdopen message log %s: %s\", fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* If asked to give up on a message, log who did it, and set the action for all the addresses. *\/ if (give_up) { struct passwd *pw = getpwuid(real_uid); log_write(0, LOG_MAIN, \"cancelled by %s\", pw ? US pw->pw_name : string_sprintf(\"uid %ld\", (long int)real_uid)); process_recipients = RECIP_FAIL; } \/* Otherwise, if there are too many Received: headers, fail all recipients. *\/ else if (received_count > received_headers_max) process_recipients = RECIP_FAIL_LOOP; \/* Otherwise, if a system-wide, address-independent message filter is specified, run it now, except in the case when we are failing all recipients as a result of timeout_frozen_after. If the system filter yields \"delivered\", then ignore the true recipients of the message. Failure of the filter file is logged, and the delivery attempt fails. *\/ else if (system_filter && process_recipients != RECIP_FAIL_TIMEOUT) { int rc; int filtertype; ugid_block ugid; redirect_block redirect; if (system_filter_uid_set) { ugid.uid = system_filter_uid; ugid.gid = system_filter_gid; ugid.uid_set = ugid.gid_set = TRUE; } else { ugid.uid_set = ugid.gid_set = FALSE; } return_path = sender_address; enable_dollar_recipients = TRUE; \/* Permit $recipients in system filter *\/ system_filtering = TRUE; \/* Any error in the filter file causes a delivery to be abandoned. *\/ redirect.string = system_filter; redirect.isfile = TRUE; redirect.check_owner = redirect.check_group = FALSE; redirect.owners = NULL; redirect.owngroups = NULL; redirect.pw = NULL; redirect.modemask = 0; DEBUG(D_deliver|D_filter) debug_printf(\"running system filter\\n\"); rc = rda_interpret( &redirect, \/* Where the data is *\/ RDO_DEFER | \/* Turn on all the enabling options *\/ RDO_FAIL | \/* Leave off all the disabling options *\/ RDO_FILTER | RDO_FREEZE | RDO_REALLOG | RDO_REWRITE, NULL, \/* No :include: restriction (not used in filter) *\/ NULL, \/* No sieve vacation directory (not sieve!) *\/ NULL, \/* No sieve enotify mailto owner (not sieve!) *\/ NULL, \/* No sieve user address (not sieve!) *\/ NULL, \/* No sieve subaddress (not sieve!) *\/ &ugid, \/* uid\/gid data *\/ &addr_new, \/* Where to hang generated addresses *\/ &filter_message, \/* Where to put error message *\/ NULL, \/* Don't skip syntax errors *\/ &filtertype, \/* Will always be set to FILTER_EXIM for this call *\/ US\"system filter\"); \/* For error messages *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter returned %d\\n\", rc); if (rc == FF_ERROR || rc == FF_NONEXIST) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN|LOG_PANIC, \"Error in system filter: %s\", string_printing(filter_message)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Reset things. If the filter message is an empty string, which can happen for a filter \"fail\" or \"freeze\" command with no text, reset it to NULL. *\/ system_filtering = FALSE; enable_dollar_recipients = FALSE; if (filter_message && filter_message[0] == 0) filter_message = NULL; \/* Save the values of the system filter variables so that user filters can use them. *\/ memcpy(filter_sn, filter_n, sizeof(filter_sn)); \/* The filter can request that delivery of the original addresses be deferred. *\/ if (rc == FF_DEFER) { process_recipients = RECIP_DEFER; deliver_msglog(\"Delivery deferred by system filter\\n\"); log_write(0, LOG_MAIN, \"Delivery deferred by system filter\"); } \/* The filter can request that a message be frozen, but this does not take place if the message has been manually thawed. In that case, we must unset \"delivered\", which is forced by the \"freeze\" command to make -bF work properly. *\/ else if (rc == FF_FREEZE && !deliver_manual_thaw) { deliver_freeze = TRUE; deliver_frozen_at = time(NULL); process_recipients = RECIP_DEFER; frozen_info = string_sprintf(\" by the system filter%s%s\", filter_message ? US\": \" : US\"\", filter_message ? filter_message : US\"\"); } \/* The filter can request that a message be failed. The error message may be quite long - it is sent back to the sender in the bounce - but we don't want to fill up the log with repetitions of it. If it starts with << then the text between << and >> is written to the log, with the rest left for the bounce message. *\/ else if (rc == FF_FAIL) { uschar *colon = US\"\"; uschar *logmsg = US\"\"; int loglen = 0; process_recipients = RECIP_FAIL_FILTER; if (filter_message) { uschar *logend; colon = US\": \"; if ( filter_message[0] == '<' && filter_message[1] == '<' && (logend = Ustrstr(filter_message, \">>\")) ) { logmsg = filter_message + 2; loglen = logend - logmsg; filter_message = logend + 2; if (filter_message[0] == 0) filter_message = NULL; } else { logmsg = filter_message; loglen = Ustrlen(filter_message); } } log_write(0, LOG_MAIN, \"cancelled by system filter%s%.*s\", colon, loglen, logmsg); } \/* Delivery can be restricted only to those recipients (if any) that the filter specified. *\/ else if (rc == FF_DELIVERED) { process_recipients = RECIP_IGNORE; if (addr_new) log_write(0, LOG_MAIN, \"original recipients ignored (system filter)\"); else log_write(0, LOG_MAIN, \"=> discarded (system filter)\"); } \/* If any new addresses were created by the filter, fake up a \"parent\" for them. This is necessary for pipes, etc., which are expected to have parents, and it also gives some sensible logging for others. Allow pipes, files, and autoreplies, and run them as the filter uid if set, otherwise as the current uid. *\/ if (addr_new) { int uid = (system_filter_uid_set)? system_filter_uid : geteuid(); int gid = (system_filter_gid_set)? system_filter_gid : getegid(); \/* The text \"system-filter\" is tested in transport_set_up_command() and in set_up_shell_command() in the pipe transport, to enable them to permit $recipients, so don't change it here without also changing it there. *\/ address_item *p = addr_new; address_item *parent = deliver_make_addr(US\"system-filter\", FALSE); parent->domain = string_copylc(qualify_domain_recipient); parent->local_part = US\"system-filter\"; \/* As part of this loop, we arrange for addr_last to end up pointing at the final address. This is used if we go on to add addresses for the original recipients. *\/ while (p) { if (parent->child_count == USHRT_MAX) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"system filter generated more \" \"than %d delivery addresses\", USHRT_MAX); parent->child_count++; p->parent = parent; if (testflag(p, af_pfr)) { uschar *tpname; uschar *type; p->uid = uid; p->gid = gid; setflag(p, af_uid_set); setflag(p, af_gid_set); setflag(p, af_allow_file); setflag(p, af_allow_pipe); setflag(p, af_allow_reply); \/* Find the name of the system filter's appropriate pfr transport *\/ if (p->address[0] == '|') { type = US\"pipe\"; tpname = system_filter_pipe_transport; address_pipe = p->address; } else if (p->address[0] == '>') { type = US\"reply\"; tpname = system_filter_reply_transport; } else { if (p->address[Ustrlen(p->address)-1] == '\/') { type = US\"directory\"; tpname = system_filter_directory_transport; } else { type = US\"file\"; tpname = system_filter_file_transport; } address_file = p->address; } \/* Now find the actual transport, first expanding the name. We have set address_file or address_pipe above. *\/ if (tpname) { uschar *tmp = expand_string(tpname); address_file = address_pipe = NULL; if (!tmp) p->message = string_sprintf(\"failed to expand \\\"%s\\\" as a \" \"system filter transport name\", tpname); tpname = tmp; } else p->message = string_sprintf(\"system_filter_%s_transport is unset\", type); if (tpname) { transport_instance *tp; for (tp = transports; tp; tp = tp->next) if (Ustrcmp(tp->name, tpname) == 0) { p->transport = tp; break; } if (!tp) p->message = string_sprintf(\"failed to find \\\"%s\\\" transport \" \"for system filter delivery\", tpname); } \/* If we couldn't set up a transport, defer the delivery, putting the error on the panic log as well as the main log. *\/ if (!p->transport) { address_item *badp = p; p = p->next; if (!addr_last) addr_new = p; else addr_last->next = p; badp->local_part = badp->address; \/* Needed for log line *\/ post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, EXIM_DTYPE_ROUTER, 0); continue; } } \/* End of pfr handling *\/ \/* Either a non-pfr delivery, or we found a transport *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter added %s\\n\", p->address); addr_last = p; p = p->next; } \/* Loop through all addr_new addresses *\/ } } \/* Scan the recipients list, and for every one that is not in the non- recipients tree, add an addr item to the chain of new addresses. If the pno value is non-negative, we must set the onetime parent from it. This which points to the relevant entry in the recipients list. This processing can be altered by the setting of the process_recipients variable, which is changed if recipients are to be ignored, failed, or deferred. This can happen as a result of system filter activity, or if the -Mg option is used to fail all of them. Duplicate addresses are handled later by a different tree structure; we can't just extend the non-recipients tree, because that will be re-written to the spool if the message is deferred, and in any case there are casing complications for local addresses. *\/ if (process_recipients != RECIP_IGNORE) for (i = 0; i < recipients_count; i++) if (!tree_search(tree_nonrecipients, recipients_list[i].address)) { recipient_item *r = recipients_list + i; address_item *new = deliver_make_addr(r->address, FALSE); new->prop.errors_address = r->errors_to; #ifdef SUPPORT_I18N if ((new->prop.utf8_msg = message_smtputf8)) { new->prop.utf8_downcvt = message_utf8_downconvert == 1; new->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1; DEBUG(D_deliver) debug_printf(\"utf8, downconvert %s\\n\", new->prop.utf8_downcvt ? \"yes\" : new->prop.utf8_downcvt_maybe ? \"ifneeded\" : \"no\"); } #endif if (r->pno >= 0) new->onetime_parent = recipients_list[r->pno].address; \/* If DSN support is enabled, set the dsn flags and the original receipt to be passed on to other DSN enabled MTAs *\/ new->dsn_flags = r->dsn_flags & rf_dsnflags; new->dsn_orcpt = r->orcpt; DEBUG(D_deliver) debug_printf(\"DSN: set orcpt: %s flags: %d\\n\", new->dsn_orcpt ? new->dsn_orcpt : US\"\", new->dsn_flags); switch (process_recipients) { \/* RECIP_DEFER is set when a system filter freezes a message. *\/ case RECIP_DEFER: new->next = addr_defer; addr_defer = new; break; \/* RECIP_FAIL_FILTER is set when a system filter has obeyed a \"fail\" command. *\/ case RECIP_FAIL_FILTER: new->message = filter_message ? filter_message : US\"delivery cancelled\"; setflag(new, af_pass_message); goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older than the value in timeout_frozen_after. Treat non-bounce messages similarly to -Mg; for bounce messages we just want to discard, so don't put the address on the failed list. The timeout has already been logged. *\/ case RECIP_FAIL_TIMEOUT: new->message = US\"delivery cancelled; message timed out\"; goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL is set when -Mg has been used. *\/ case RECIP_FAIL: new->message = US\"delivery cancelled by administrator\"; \/* Fall through *\/ \/* Common code for the failure cases above. If this is not a bounce message, put the address on the failed list so that it is used to create a bounce. Otherwise do nothing - this just discards the address. The incident has already been logged. *\/ RECIP_QUEUE_FAILED: if (sender_address[0] != 0) { new->next = addr_failed; addr_failed = new; } break; \/* RECIP_FAIL_LOOP is set when there are too many Received: headers in the message. Process each address as a routing failure; if this is a bounce message, it will get frozen. *\/ case RECIP_FAIL_LOOP: new->message = US\"Too many \\\"Received\\\" headers - suspected mail loop\"; post_process_one(new, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); break; \/* Value should be RECIP_ACCEPT; take this as the safe default. *\/ default: if (!addr_new) addr_new = new; else addr_last->next = new; addr_last = new; break; } #ifndef DISABLE_EVENT if (process_recipients != RECIP_ACCEPT) { uschar * save_local = deliver_localpart; const uschar * save_domain = deliver_domain; deliver_localpart = expand_string( string_sprintf(\"${local_part:%s}\", new->address)); deliver_domain = expand_string( string_sprintf(\"${domain:%s}\", new->address)); (void) event_raise(event_action, US\"msg:fail:internal\", new->message); deliver_localpart = save_local; deliver_domain = save_domain; } #endif } DEBUG(D_deliver) { address_item *p; debug_printf(\"Delivery address list:\\n\"); for (p = addr_new; p; p = p->next) debug_printf(\" %s %s\\n\", p->address, p->onetime_parent ? p->onetime_parent : US\"\"); } \/* Set up the buffers used for copying over the file when delivering. *\/ deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE); deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE); \/* Until there are no more new addresses, handle each one as follows: . If this is a generated address (indicated by the presence of a parent pointer) then check to see whether it is a pipe, file, or autoreply, and if so, handle it directly here. The router that produced the address will have set the allow flags into the address, and also set the uid\/gid required. Having the routers generate new addresses and then checking them here at the outer level is tidier than making each router do the checking, and means that routers don't need access to the failed address queue. . Break up the address into local part and domain, and make lowercased versions of these strings. We also make unquoted versions of the local part. . Handle the percent hack for those domains for which it is valid. . For child addresses, determine if any of the parents have the same address. If so, generate a different string for previous delivery checking. Without this code, if the address spqr generates spqr via a forward or alias file, delivery of the generated spqr stops further attempts at the top level spqr, which is not what is wanted - it may have generated other addresses. . Check on the retry database to see if routing was previously deferred, but only if in a queue run. Addresses that are to be routed are put on the addr_route chain. Addresses that are to be deferred are put on the addr_defer chain. We do all the checking first, so as not to keep the retry database open any longer than necessary. . Now we run the addresses through the routers. A router may put the address on either the addr_local or the addr_remote chain for local or remote delivery, respectively, or put it on the addr_failed chain if it is undeliveable, or it may generate child addresses and put them on the addr_new chain, or it may defer an address. All the chain anchors are passed as arguments so that the routers can be called for verification purposes as well. . If new addresses have been generated by the routers, da capo. *\/ header_rewritten = FALSE; \/* No headers rewritten yet *\/ while (addr_new) \/* Loop until all addresses dealt with *\/ { address_item *addr, *parent; \/* Failure to open the retry database is treated the same as if it does not exist. In both cases, dbm_file is NULL. *\/ if (!(dbm_file = dbfn_open(US\"retry\", O_RDONLY, &dbblock, FALSE))) DEBUG(D_deliver|D_retry|D_route|D_hints_lookup) debug_printf(\"no retry data available\\n\"); \/* Scan the current batch of new addresses, to handle pipes, files and autoreplies, and determine which others are ready for routing. *\/ while (addr_new) { int rc; uschar *p; tree_node *tnode; dbdata_retry *domain_retry_record; dbdata_retry *address_retry_record; addr = addr_new; addr_new = addr->next; DEBUG(D_deliver|D_retry|D_route) { debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"Considering: %s\\n\", addr->address); } \/* Handle generated address that is a pipe or a file or an autoreply. *\/ if (testflag(addr, af_pfr)) { \/* If an autoreply in a filter could not generate a syntactically valid address, give up forthwith. Set af_ignore_error so that we don't try to generate a bounce. *\/ if (testflag(addr, af_bad_reply)) { addr->basic_errno = ERRNO_BADADDRESS2; addr->local_part = addr->address; addr->message = US\"filter autoreply generated syntactically invalid recipient\"; addr->prop.ignore_error = TRUE; (void) post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If two different users specify delivery to the same pipe or file or autoreply, there should be two different deliveries, so build a unique string that incorporates the original address, and use this for duplicate testing and recording delivery, and also for retrying. *\/ addr->unique = string_sprintf(\"%s:%s\", addr->address, addr->parent->unique + (testflag(addr->parent, af_homonym)? 3:0)); addr->address_retry_key = addr->domain_retry_key = string_sprintf(\"T:%s\", addr->unique); \/* If a filter file specifies two deliveries to the same pipe or file, we want to de-duplicate, but this is probably not wanted for two mail commands to the same address, where probably both should be delivered. So, we have to invent a different unique string in that case. Just keep piling '>' characters on the front. *\/ if (addr->address[0] == '>') { while (tree_search(tree_duplicates, addr->unique)) addr->unique = string_sprintf(\">%s\", addr->unique); } else if ((tnode = tree_search(tree_duplicates, addr->unique))) { DEBUG(D_deliver|D_route) debug_printf(\"%s is a duplicate address: discarded\\n\", addr->address); addr->dupof = tnode->data.ptr; addr->next = addr_duplicate; addr_duplicate = addr; continue; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); \/* Check for previous delivery *\/ if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->address); child_done(addr, tod_stamp(tod_log)); continue; } \/* Save for checking future duplicates *\/ tree_add_duplicate(addr->unique, addr); \/* Set local part and domain *\/ addr->local_part = addr->address; addr->domain = addr->parent->domain; \/* Ensure that the delivery is permitted. *\/ if (testflag(addr, af_file)) { if (!testflag(addr, af_allow_file)) { addr->basic_errno = ERRNO_FORBIDFILE; addr->message = US\"delivery to file forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (addr->address[0] == '|') { if (!testflag(addr, af_allow_pipe)) { addr->basic_errno = ERRNO_FORBIDPIPE; addr->message = US\"delivery to pipe forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (!testflag(addr, af_allow_reply)) { addr->basic_errno = ERRNO_FORBIDREPLY; addr->message = US\"autoreply forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If the errno field is already set to BADTRANSPORT, it indicates failure to expand a transport string, or find the associated transport, or an unset transport when one is required. Leave this test till now so that the forbid errors are given in preference. *\/ if (addr->basic_errno == ERRNO_BADTRANSPORT) { (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; } \/* Treat \/dev\/null as a special case and abandon the delivery. This avoids having to specify a uid on the transport just for this case. Arrange for the transport name to be logged as \"**bypassed**\". *\/ if (Ustrcmp(addr->address, \"\/dev\/null\") == 0) { uschar *save = addr->transport->name; addr->transport->name = US\"**bypassed**\"; (void)post_process_one(addr, OK, LOG_MAIN, EXIM_DTYPE_TRANSPORT, '='); addr->transport->name = save; continue; \/* with the next new address *\/ } \/* Pipe, file, or autoreply delivery is to go ahead as a normal local delivery. *\/ DEBUG(D_deliver|D_route) debug_printf(\"queued for %s transport\\n\", addr->transport->name); addr->next = addr_local; addr_local = addr; continue; \/* with the next new address *\/ } \/* Handle normal addresses. First, split up into local part and domain, handling the %-hack if necessary. There is the possibility of a defer from a lookup in percent_hack_domains. *\/ if ((rc = deliver_split_address(addr)) == DEFER) { addr->message = US\"cannot check percent_hack_domains\"; addr->basic_errno = ERRNO_LISTDEFER; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Check to see if the domain is held. If so, proceed only if the delivery was forced by hand. *\/ deliver_domain = addr->domain; \/* set $domain *\/ if ( !forced && hold_domains && (rc = match_isinlist(addr->domain, (const uschar **)&hold_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != FAIL ) { if (rc == DEFER) { addr->message = US\"hold_domains lookup deferred\"; addr->basic_errno = ERRNO_LISTDEFER; } else { addr->message = US\"domain is held\"; addr->basic_errno = ERRNO_HELD; } (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Now we can check for duplicates and previously delivered addresses. In order to do this, we have to generate a \"unique\" value for each address, because there may be identical actual addresses in a line of descendents. The \"unique\" field is initialized to the same value as the \"address\" field, but gets changed here to cope with identically-named descendents. *\/ for (parent = addr->parent; parent; parent = parent->parent) if (strcmpic(addr->address, parent->address) == 0) break; \/* If there's an ancestor with the same name, set the homonym flag. This influences how deliveries are recorded. Then add a prefix on the front of the unique address. We use \\n\\ where n starts at 0 and increases each time. It is unlikely to pass 9, but if it does, it may look odd but will still work. This means that siblings or cousins with the same names are treated as duplicates, which is what we want. *\/ if (parent) { setflag(addr, af_homonym); if (parent->unique[0] != '\\\\') addr->unique = string_sprintf(\"\\\\0\\\\%s\", addr->address); else addr->unique = string_sprintf(\"\\\\%c\\\\%s\", parent->unique[1] + 1, addr->address); } \/* Ensure that the domain in the unique field is lower cased, because domains are always handled caselessly. *\/ p = Ustrrchr(addr->unique, '@'); while (*p != 0) { *p = tolower(*p); p++; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->unique); child_done(addr, tod_stamp(tod_log)); continue; } \/* Get the routing retry status, saving the two retry keys (with and without the local part) for subsequent use. If there is no retry record for the standard address routing retry key, we look for the same key with the sender attached, because this form is used by the smtp transport after a 4xx response to RCPT when address_retry_include_sender is true. *\/ addr->domain_retry_key = string_sprintf(\"R:%s\", addr->domain); addr->address_retry_key = string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain); if (dbm_file) { domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key); if ( domain_retry_record && now - domain_retry_record->time_stamp > retry_data_expire ) domain_retry_record = NULL; \/* Ignore if too old *\/ address_retry_record = dbfn_read(dbm_file, addr->address_retry_key); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire ) address_retry_record = NULL; \/* Ignore if too old *\/ if (!address_retry_record) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); address_retry_record = dbfn_read(dbm_file, altkey); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire) address_retry_record = NULL; \/* Ignore if too old *\/ } } else domain_retry_record = address_retry_record = NULL; DEBUG(D_deliver|D_retry) { if (!domain_retry_record) debug_printf(\"no domain retry record\\n\"); if (!address_retry_record) debug_printf(\"no address retry record\\n\"); } \/* If we are sending a message down an existing SMTP connection, we must assume that the message which created the connection managed to route an address to that connection. We do not want to run the risk of taking a long time over routing here, because if we do, the server at the other end of the connection may time it out. This is especially true for messages with lots of addresses. For this kind of delivery, queue_running is not set, so we would normally route all addresses. We take a pragmatic approach and defer routing any addresses that have any kind of domain retry record. That is, we don't even look at their retry times. It doesn't matter if this doesn't work occasionally. This is all just an optimization, after all. The reason for not doing the same for address retries is that they normally arise from 4xx responses, not DNS timeouts. *\/ if (continue_hostname && domain_retry_record) { addr->message = US\"reusing SMTP connection skips previous routing defer\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* If we are in a queue run, defer routing unless there is no retry data or we've passed the next retry time, or this message is forced. In other words, ignore retry data when not in a queue run. However, if the domain retry time has expired, always allow the routing attempt. If it fails again, the address will be failed. This ensures that each address is routed at least once, even after long-term routing failures. If there is an address retry, check that too; just wait for the next retry time. This helps with the case when the temporary error on the address was really message-specific rather than address specific, since it allows other messages through. We also wait for the next retry time if this is a message sent down an existing SMTP connection (even though that will be forced). Otherwise there will be far too many attempts for an address that gets a 4xx error. In fact, after such an error, we should not get here because, the host should not be remembered as one this message needs. However, there was a bug that used to cause this to happen, so it is best to be on the safe side. Even if we haven't reached the retry time in the hints, there is one more check to do, which is for the ultimate address timeout. We only do this check if there is an address retry record and there is not a domain retry record; this implies that previous attempts to handle the address had the retry_use_local_parts option turned on. We use this as an approximation for the destination being like a local delivery, for example delivery over LMTP to an IMAP message store. In this situation users are liable to bump into their quota and thereby have intermittently successful deliveries, which keep the retry record fresh, which can lead to us perpetually deferring messages. *\/ else if ( ( queue_running && !deliver_force || continue_hostname ) && ( ( domain_retry_record && now < domain_retry_record->next_try && !domain_retry_record->expired ) || ( address_retry_record && now < address_retry_record->next_try ) ) && ( domain_retry_record || !address_retry_record || !retry_ultimate_address_timeout(addr->address_retry_key, addr->domain, address_retry_record, now) ) ) { addr->message = US\"retry time not reached\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* The domain is OK for routing. Remember if retry data exists so it can be cleaned up after a successful delivery. *\/ else { if (domain_retry_record || address_retry_record) setflag(addr, af_dr_retry_exists); addr->next = addr_route; addr_route = addr; DEBUG(D_deliver|D_route) debug_printf(\"%s: queued for routing\\n\", addr->address); } } \/* The database is closed while routing is actually happening. Requests to update it are put on a chain and all processed together at the end. *\/ if (dbm_file) dbfn_close(dbm_file); \/* If queue_domains is set, we don't even want to try routing addresses in those domains. During queue runs, queue_domains is forced to be unset. Optimize by skipping this pass through the addresses if nothing is set. *\/ if (!deliver_force && queue_domains) { address_item *okaddr = NULL; while (addr_route) { address_item *addr = addr_route; addr_route = addr->next; deliver_domain = addr->domain; \/* set $domain *\/ if ((rc = match_isinlist(addr->domain, (const uschar **)&queue_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != OK) if (rc == DEFER) { addr->basic_errno = ERRNO_LISTDEFER; addr->message = US\"queue_domains lookup deferred\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } else { addr->next = okaddr; okaddr = addr; } else { addr->basic_errno = ERRNO_QUEUE_DOMAIN; addr->message = US\"domain is in queue_domains\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } } addr_route = okaddr; } \/* Now route those addresses that are not deferred. *\/ while (addr_route) { int rc; address_item *addr = addr_route; const uschar *old_domain = addr->domain; uschar *old_unique = addr->unique; addr_route = addr->next; addr->next = NULL; \/* Just in case some router parameter refers to it. *\/ if (!(return_path = addr->prop.errors_address)) return_path = sender_address; \/* If a router defers an address, add a retry item. Whether or not to use the local part in the key is a property of the router. *\/ if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new, &addr_succeed, v_none)) == DEFER) retry_add_item(addr, addr->router->retry_use_local_part ? string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain) : string_sprintf(\"R:%s\", addr->domain), 0); \/* Otherwise, if there is an existing retry record in the database, add retry items to delete both forms. We must also allow for the possibility of a routing retry that includes the sender address. Since the domain might have been rewritten (expanded to fully qualified) as a result of routing, ensure that the rewritten form is also deleted. *\/ else if (testflag(addr, af_dr_retry_exists)) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); retry_add_item(addr, altkey, rf_delete); retry_add_item(addr, addr->address_retry_key, rf_delete); retry_add_item(addr, addr->domain_retry_key, rf_delete); if (Ustrcmp(addr->domain, old_domain) != 0) retry_add_item(addr, string_sprintf(\"R:%s\", old_domain), rf_delete); } \/* DISCARD is given for :blackhole: and \"seen finish\". The event has been logged, but we need to ensure the address (and maybe parents) is marked done. *\/ if (rc == DISCARD) { address_done(addr, tod_stamp(tod_log)); continue; \/* route next address *\/ } \/* The address is finished with (failed or deferred). *\/ if (rc != OK) { (void)post_process_one(addr, rc, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* route next address *\/ } \/* The address has been routed. If the router changed the domain, it will also have changed the unique address. We have to test whether this address has already been delivered, because it's the unique address that finally gets recorded. *\/ if ( addr->unique != old_unique && tree_search(tree_nonrecipients, addr->unique) != 0 ) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: \" \"discarded\\n\", addr->address); if (addr_remote == addr) addr_remote = addr->next; else if (addr_local == addr) addr_local = addr->next; } \/* If the router has same_domain_copy_routing set, we are permitted to copy the routing for any other addresses with the same domain. This is an optimisation to save repeated DNS lookups for \"standard\" remote domain routing. The option is settable only on routers that generate host lists. We play it very safe, and do the optimization only if the address is routed to a remote transport, there are no header changes, and the domain was not modified by the router. *\/ if ( addr_remote == addr && addr->router->same_domain_copy_routing && !addr->prop.extra_headers && !addr->prop.remove_headers && old_domain == addr->domain ) { address_item **chain = &addr_route; while (*chain) { address_item *addr2 = *chain; if (Ustrcmp(addr2->domain, addr->domain) != 0) { chain = &(addr2->next); continue; } \/* Found a suitable address; take it off the routing list and add it to the remote delivery list. *\/ *chain = addr2->next; addr2->next = addr_remote; addr_remote = addr2; \/* Copy the routing data *\/ addr2->domain = addr->domain; addr2->router = addr->router; addr2->transport = addr->transport; addr2->host_list = addr->host_list; addr2->fallback_hosts = addr->fallback_hosts; addr2->prop.errors_address = addr->prop.errors_address; copyflag(addr2, addr, af_hide_child); copyflag(addr2, addr, af_local_host_removed); DEBUG(D_deliver|D_route) debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\" \"routing %s\\n\" \"Routing for %s copied from %s\\n\", addr2->address, addr2->address, addr->address); } } } \/* Continue with routing the next address. *\/ } \/* Loop to process any child addresses that the routers created, and any rerouted addresses that got put back on the new chain. *\/ \/* Debugging: show the results of the routing *\/ DEBUG(D_deliver|D_retry|D_route) { address_item *p; debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"After routing:\\n Local deliveries:\\n\"); for (p = addr_local; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Remote deliveries:\\n\"); for (p = addr_remote; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Failed addresses:\\n\"); for (p = addr_failed; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Deferred addresses:\\n\"); for (p = addr_defer; p; p = p->next) debug_printf(\" %s\\n\", p->address); } \/* Free any resources that were cached during routing. *\/ search_tidyup(); route_tidyup(); \/* These two variables are set only during routing, after check_local_user. Ensure they are not set in transports. *\/ local_user_gid = (gid_t)(-1); local_user_uid = (uid_t)(-1); \/* Check for any duplicate addresses. This check is delayed until after routing, because the flexibility of the routing configuration means that identical addresses with different parentage may end up being redirected to different addresses. Checking for duplicates too early (as we previously used to) makes this kind of thing not work. *\/ do_duplicate_check(&addr_local); do_duplicate_check(&addr_remote); \/* When acting as an MUA wrapper, we proceed only if all addresses route to a remote transport. The check that they all end up in one transaction happens in the do_remote_deliveries() function. *\/ if ( mua_wrapper && (addr_local || addr_failed || addr_defer) ) { address_item *addr; uschar *which, *colon, *msg; if (addr_local) { addr = addr_local; which = US\"local\"; } else if (addr_defer) { addr = addr_defer; which = US\"deferred\"; } else { addr = addr_failed; which = US\"failed\"; } while (addr->parent) addr = addr->parent; if (addr->message) { colon = US\": \"; msg = addr->message; } else colon = msg = US\"\"; \/* We don't need to log here for a forced failure as it will already have been logged. Defer will also have been logged, but as a defer, so we do need to do the failure logging. *\/ if (addr != addr_failed) log_write(0, LOG_MAIN, \"** %s routing yielded a %s delivery\", addr->address, which); \/* Always write an error to the caller *\/ fprintf(stderr, \"routing %s yielded a %s delivery%s%s\\n\", addr->address, which, colon, msg); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* If this is a run to continue deliveries to an external channel that is already set up, defer any local deliveries. *\/ if (continue_transport) { if (addr_defer) { address_item *addr = addr_defer; while (addr->next) addr = addr->next; addr->next = addr_local; } else addr_defer = addr_local; addr_local = NULL; } \/* Because address rewriting can happen in the routers, we should not really do ANY deliveries until all addresses have been routed, so that all recipients of the message get the same headers. However, this is in practice not always possible, since sometimes remote addresses give DNS timeouts for days on end. The pragmatic approach is to deliver what we can now, saving any rewritten headers so that at least the next lot of recipients benefit from the rewriting that has already been done. If any headers have been rewritten during routing, update the spool file to remember them for all subsequent deliveries. This can be delayed till later if there is only address to be delivered - if it succeeds the spool write need not happen. *\/ if ( header_rewritten && ( addr_local && (addr_local->next || addr_remote) || addr_remote && addr_remote->next ) ) { \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); header_rewritten = FALSE; } \/* If there are any deliveries to be and we do not already have the journal file, create it. This is used to record successful deliveries as soon as possible after each delivery is known to be complete. A file opened with O_APPEND is used so that several processes can run simultaneously. The journal is just insurance against crashes. When the spool file is ultimately updated at the end of processing, the journal is deleted. If a journal is found to exist at the start of delivery, the addresses listed therein are added to the non-recipients. *\/ if (addr_local || addr_remote) { if (journal_fd < 0) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if ((journal_fd = Uopen(fname, #ifdef O_CLOEXEC O_CLOEXEC | #endif O_WRONLY|O_APPEND|O_CREAT|O_EXCL, SPOOL_MODE)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't open journal file %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } \/* Set the close-on-exec flag, make the file owned by Exim, and ensure that the mode is correct - the group setting doesn't always seem to get set automatically. *\/ if( fchown(journal_fd, exim_uid, exim_gid) || fchmod(journal_fd, SPOOL_MODE) #ifndef O_CLOEXEC || fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC) #endif ) { int ret = Uunlink(fname); log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't set perms on journal file %s: %s\", fname, strerror(errno)); if(ret && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } } } else if (journal_fd >= 0) { close(journal_fd); journal_fd = -1; } \/* Now we can get down to the business of actually doing deliveries. Local deliveries are done first, then remote ones. If ever the problems of how to handle fallback transports are figured out, this section can be put into a loop for handling fallbacks, though the uid switching will have to be revised. *\/ \/* Precompile a regex that is used to recognize a parameter in response to an LHLO command, if is isn't already compiled. This may be used on both local and remote LMTP deliveries. *\/ if (!regex_IGNOREQUOTA) regex_IGNOREQUOTA = regex_must_compile(US\"\\\\n250[\\\\s\\\\-]IGNOREQUOTA(\\\\s|\\\\n|$)\", FALSE, TRUE); \/* Handle local deliveries *\/ if (addr_local) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\\n\"); do_local_deliveries(); disable_logging = FALSE; } \/* If queue_run_local is set, we do not want to attempt any remote deliveries, so just queue them all. *\/ if (queue_run_local) while (addr_remote) { address_item *addr = addr_remote; addr_remote = addr->next; addr->next = NULL; addr->basic_errno = ERRNO_LOCAL_ONLY; addr->message = US\"remote deliveries suppressed\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_TRANSPORT, 0); } \/* Handle remote deliveries *\/ if (addr_remote) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\\n\"); \/* Precompile some regex that are used to recognize parameters in response to an EHLO command, if they aren't already compiled. *\/ deliver_init(); \/* Now sort the addresses if required, and do the deliveries. The yield of do_remote_deliveries is FALSE when mua_wrapper is set and all addresses cannot be delivered in one transaction. *\/ if (remote_sort_domains) sort_remote_deliveries(); if (!do_remote_deliveries(FALSE)) { log_write(0, LOG_MAIN, \"** mua_wrapper is set but recipients cannot all \" \"be delivered in one transaction\"); fprintf(stderr, \"delivery to smarthost failed (configuration problem)\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* See if any of the addresses that failed got put on the queue for delivery to their fallback hosts. We do it this way because often the same fallback host is used for many domains, so all can be sent in a single transaction (if appropriately configured). *\/ if (addr_fallback && !mua_wrapper) { DEBUG(D_deliver) debug_printf(\"Delivering to fallback hosts\\n\"); addr_remote = addr_fallback; addr_fallback = NULL; if (remote_sort_domains) sort_remote_deliveries(); do_remote_deliveries(TRUE); } disable_logging = FALSE; } \/* All deliveries are now complete. Ignore SIGTERM during this tidying up phase, to minimize cases of half-done things. *\/ DEBUG(D_deliver) debug_printf(\">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\\n\"); cancel_cutthrough_connection(TRUE, US\"deliveries are done\"); \/* Root privilege is no longer needed *\/ exim_setugid(exim_uid, exim_gid, FALSE, US\"post-delivery tidying\"); set_process_info(\"tidying up after delivering %s\", message_id); signal(SIGTERM, SIG_IGN); \/* When we are acting as an MUA wrapper, the smtp transport will either have succeeded for all addresses, or failed them all in normal cases. However, there are some setup situations (e.g. when a named port does not exist) that cause an immediate exit with deferral of all addresses. Convert those into failures. We do not ever want to retry, nor do we want to send a bounce message. *\/ if (mua_wrapper) { if (addr_defer) { address_item *addr, *nextaddr; for (addr = addr_defer; addr; addr = nextaddr) { log_write(0, LOG_MAIN, \"** %s mua_wrapper forced failure for deferred \" \"delivery\", addr->address); nextaddr = addr->next; addr->next = addr_failed; addr_failed = addr; } addr_defer = NULL; } \/* Now all should either have succeeded or failed. *\/ if (!addr_failed) final_yield = DELIVER_MUA_SUCCEEDED; else { host_item * host; uschar *s = addr_failed->user_message; if (!s) s = addr_failed->message; fprintf(stderr, \"Delivery failed: \"); if (addr_failed->basic_errno > 0) { fprintf(stderr, \"%s\", strerror(addr_failed->basic_errno)); if (s) fprintf(stderr, \": \"); } if ((host = addr_failed->host_used)) fprintf(stderr, \"H=%s [%s]: \", host->name, host->address); if (s) fprintf(stderr, \"%s\", CS s); else if (addr_failed->basic_errno <= 0) fprintf(stderr, \"unknown error\"); fprintf(stderr, \"\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = NULL; } } \/* In a normal configuration, we now update the retry database. This is done in one fell swoop at the end in order not to keep opening and closing (and locking) the database. The code for handling retries is hived off into a separate module for convenience. We pass it the addresses of the various chains, because deferred addresses can get moved onto the failed chain if the retry cutoff time has expired for all alternative destinations. Bypass the updating of the database if the -N flag is set, which is a debugging thing that prevents actual delivery. *\/ else if (!dont_deliver) retry_update(&addr_defer, &addr_failed, &addr_succeed); \/* Send DSN for successful messages if requested *\/ addr_senddsn = NULL; for (addr_dsntmp = addr_succeed; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { \/* af_ignore_error not honored here. it's not an error *\/ DEBUG(D_deliver) debug_printf(\"DSN: processing router : %s\\n\" \"DSN: processing successful delivery address: %s\\n\" \"DSN: Sender_address: %s\\n\" \"DSN: orcpt: %s flags: %d\\n\" \"DSN: envid: %s ret: %d\\n\" \"DSN: Final recipient: %s\\n\" \"DSN: Remote SMTP server supports DSN: %d\\n\", addr_dsntmp->router ? addr_dsntmp->router->name : US\"(unknown)\", addr_dsntmp->address, sender_address, addr_dsntmp->dsn_orcpt ? addr_dsntmp->dsn_orcpt : US\"NULL\", addr_dsntmp->dsn_flags, dsn_envid ? dsn_envid : US\"NULL\", dsn_ret, addr_dsntmp->address, addr_dsntmp->dsn_aware ); \/* send report if next hop not DSN aware or a router flagged \"last DSN hop\" and a report was requested *\/ if ( ( addr_dsntmp->dsn_aware != dsn_support_yes || addr_dsntmp->dsn_flags & rf_dsnlasthop ) && addr_dsntmp->dsn_flags & rf_dsnflags && addr_dsntmp->dsn_flags & rf_notify_success ) { \/* copy and relink address_item and send report with all of them at once later *\/ address_item * addr_next = addr_senddsn; addr_senddsn = store_get(sizeof(address_item)); *addr_senddsn = *addr_dsntmp; addr_senddsn->next = addr_next; } else DEBUG(D_deliver) debug_printf(\"DSN: not sending DSN success message\\n\"); } if (addr_senddsn) { pid_t pid; int fd; \/* create exim process to send message *\/ pid = child_open_exim(&fd); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim returns: %d\\n\", pid); if (pid < 0) \/* Creation of child failed *\/ { log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim failed\\n\"); } else \/* Creation of child succeeded *\/ { FILE *f = fdopen(fd, \"wb\"); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ uschar * bound; transport_ctx tctx = {{0}}; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", sender_address); \/* build unique id for MIME boundary *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); DEBUG(D_deliver) debug_printf(\"DSN: MIME boundary: %s\\n\", bound); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-generated\\n\" \"From: Mail Delivery System \\n\" \"To: %s\\n\" \"Subject: Delivery Status Notification\\n\" \"Content-Type: multipart\/report; report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\\n\" \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\" \"This message was created automatically by mail delivery software.\\n\" \" ----- The following addresses had successful delivery notifications -----\\n\", qualify_domain_sender, sender_address, bound, bound); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) fprintf(f, \"<%s> (relayed %s)\\n\\n\", addr_dsntmp->address, (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? \"via non DSN router\" : addr_dsntmp->dsn_aware == dsn_support_no ? \"to non-DSN-aware mailer\" : \"via non \\\"Remote SMTP\\\" router\" ); fprintf(f, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { if (addr_dsntmp->dsn_orcpt) fprintf(f,\"Original-Recipient: %s\\n\", addr_dsntmp->dsn_orcpt); fprintf(f, \"Action: delivered\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 2.0.0\\n\", addr_dsntmp->address); if (addr_dsntmp->host_used && addr_dsntmp->host_used->name) fprintf(f, \"Remote-MTA: dns; %s\\nDiagnostic-Code: smtp; 250 Ok\\n\\n\", addr_dsntmp->host_used->name); else fprintf(f, \"Diagnostic-Code: X-Exim; relayed via non %s router\\n\\n\", (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? \"DSN\" : \"SMTP\"); } fprintf(f, \"--%s\\nContent-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); fclose(f); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ } } \/* If any addresses failed, we must send a message to somebody, unless af_ignore_error is set, in which case no action is taken. It is possible for several messages to get sent if there are addresses with different requirements. *\/ while (addr_failed) { pid_t pid; int fd; uschar *logtod = tod_stamp(tod_log); address_item *addr; address_item *handled_addr = NULL; address_item **paddr; address_item *msgchain = NULL; address_item **pmsgchain = &msgchain; \/* There are weird cases when logging is disabled in the transport. However, there may not be a transport (address failed by a router). *\/ disable_logging = FALSE; if (addr_failed->transport) disable_logging = addr_failed->transport->disable_logging; DEBUG(D_deliver) debug_printf(\"processing failed address %s\\n\", addr_failed->address); \/* There are only two ways an address in a bounce message can get here: (1) When delivery was initially deferred, but has now timed out (in the call to retry_update() above). We can detect this by testing for af_retry_timedout. If the address does not have its own errors address, we arrange to ignore the error. (2) If delivery failures for bounce messages are being ignored. We can detect this by testing for af_ignore_error. This will also be set if a bounce message has been autothawed and the ignore_bounce_errors_after time has passed. It might also be set if a router was explicitly configured to ignore errors (errors_to = \"\"). If neither of these cases obtains, something has gone wrong. Log the incident, but then ignore the error. *\/ if (sender_address[0] == 0 && !addr_failed->prop.errors_address) { if ( !testflag(addr_failed, af_retry_timedout) && !addr_failed->prop.ignore_error) log_write(0, LOG_MAIN|LOG_PANIC, \"internal error: bounce message \" \"failure is neither frozen nor ignored (it's been ignored)\"); addr_failed->prop.ignore_error = TRUE; } \/* If the first address on the list has af_ignore_error set, just remove it from the list, throw away any saved message file, log it, and mark the recipient done. *\/ if ( addr_failed->prop.ignore_error || ( addr_failed->dsn_flags & rf_dsnflags && (addr_failed->dsn_flags & rf_notify_failure) != rf_notify_failure ) ) { addr = addr_failed; addr_failed = addr->next; if (addr->return_filename) Uunlink(addr->return_filename); log_write(0, LOG_MAIN, \"%s%s%s%s: error ignored\", addr->address, !addr->parent ? US\"\" : US\" <\", !addr->parent ? US\"\" : addr->parent->address, !addr->parent ? US\"\" : US\">\"); address_done(addr, logtod); child_done(addr, logtod); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Otherwise, handle the sending of a message. Find the error address for the first address, then send a message that includes all failed addresses that have the same error address. Note the bounce_recipient is a global so that it can be accessed by $bounce_recipient while creating a customized error message. *\/ else { if (!(bounce_recipient = addr_failed->prop.errors_address)) bounce_recipient = sender_address; \/* Make a subprocess to send a message *\/ if ((pid = child_open_exim(&fd)) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); \/* Creation of child succeeded *\/ else { int ch, rc; int filecount = 0; int rcount = 0; uschar *bcc, *emf_text; FILE *f = fdopen(fd, \"wb\"); FILE *emf = NULL; BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0; int max = (bounce_return_size_limit\/DELIVER_IN_BUFFER_SIZE + 1) * DELIVER_IN_BUFFER_SIZE; uschar * bound; uschar *dsnlimitmsg; uschar *dsnnotifyhdr; int topt; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", bounce_recipient); \/* Scan the addresses for all that have the same errors address, removing them from the addr_failed chain, and putting them on msgchain. *\/ paddr = &addr_failed; for (addr = addr_failed; addr; addr = *paddr) if (Ustrcmp(bounce_recipient, addr->prop.errors_address ? addr->prop.errors_address : sender_address) == 0) { \/* The same - dechain *\/ *paddr = addr->next; *pmsgchain = addr; addr->next = NULL; pmsgchain = &(addr->next); } else paddr = &addr->next; \/* Not the same; skip *\/ \/* Include X-Failed-Recipients: for automatic interpretation, but do not let any one header line get too long. We do this by starting a new header every 50 recipients. Omit any addresses for which the \"hide_child\" flag is set. *\/ for (addr = msgchain; addr; addr = addr->next) { if (testflag(addr, af_hide_child)) continue; if (rcount >= 50) { fprintf(f, \"\\n\"); rcount = 0; } fprintf(f, \"%s%s\", rcount++ == 0 ? \"X-Failed-Recipients: \" : \",\\n \", testflag(addr, af_pfr) && addr->parent ? string_printing(addr->parent->address) : string_printing(addr->address)); } if (rcount > 0) fprintf(f, \"\\n\"); \/* Output the standard headers *\/ if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(f); fprintf(f, \"To: %s\\n\", bounce_recipient); \/* generate boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(f, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); \/* Open a template file if one is provided. Log failure to open, but carry on - default texts will be used. *\/ if (bounce_message_file) if (!(emf = Ufopen(bounce_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for error \" \"message texts: %s\", bounce_message_file, strerror(errno)); \/* Quietly copy to configured additional addresses if required. *\/ if ((bcc = moan_check_errorcopy(bounce_recipient))) fprintf(f, \"Bcc: %s\\n\", bcc); \/* The texts for the message can be read from a template file; if there isn't one, or if it is too short, built-in texts are used. The first emf text is a Subject: and any other headers. *\/ if ((emf_text = next_emf(emf, US\"header\"))) fprintf(f, \"%s\\n\", emf_text); else fprintf(f, \"Subject: Mail delivery failed%s\\n\\n\", to_sender? \": returning message to sender\" : \"\"); \/* output human readable part as text\/plain section *\/ fprintf(f, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((emf_text = next_emf(emf, US\"intro\"))) fprintf(f, \"%s\", CS emf_text); else { fprintf(f, \/* This message has been reworded several times. It seems to be confusing to somebody, however it is worded. I have retreated to the original, simple wording. *\/ \"This message was created automatically by mail delivery software.\\n\"); if (bounce_message_text) fprintf(f, \"%s\", CS bounce_message_text); if (to_sender) fprintf(f, \"\\nA message that you sent could not be delivered to one or more of its\\n\" \"recipients. This is a permanent error. The following address(es) failed:\\n\"); else fprintf(f, \"\\nA message sent by\\n\\n <%s>\\n\\n\" \"could not be delivered to one or more of its recipients. The following\\n\" \"address(es) failed:\\n\", sender_address); } fputc('\\n', f); \/* Process the addresses, leaving them on the msgchain if they have a file name for a return message. (There has already been a check in post_process_one() for the existence of data in the message file.) A TRUE return from print_address_information() means that the address is not hidden. *\/ paddr = &msgchain; for (addr = msgchain; addr; addr = *paddr) { if (print_address_information(addr, f, US\" \", US\"\\n \", US\"\")) print_address_error(addr, f, US\"\"); \/* End the final line for the address *\/ fputc('\\n', f); \/* Leave on msgchain if there's a return file. *\/ if (addr->return_file >= 0) { paddr = &(addr->next); filecount++; } \/* Else save so that we can tick off the recipient when the message is sent. *\/ else { *paddr = addr->next; addr->next = handled_addr; handled_addr = addr; } } fputc('\\n', f); \/* Get the next text, whether we need it or not, so as to be positioned for the one after. *\/ emf_text = next_emf(emf, US\"generated text\"); \/* If there were any file messages passed by the local transports, include them in the message. Then put the address on the handled chain. In the case of a batch of addresses that were all sent to the same transport, the return_file field in all of them will contain the same fd, and the return_filename field in the *last* one will be set (to the name of the file). *\/ if (msgchain) { address_item *nextaddr; if (emf_text) fprintf(f, \"%s\", CS emf_text); else fprintf(f, \"The following text was generated during the delivery \" \"attempt%s:\\n\", (filecount > 1)? \"s\" : \"\"); for (addr = msgchain; addr; addr = nextaddr) { FILE *fm; address_item *topaddr = addr; \/* List all the addresses that relate to this file *\/ fputc('\\n', f); while(addr) \/* Insurance *\/ { print_address_information(addr, f, US\"------ \", US\"\\n \", US\" ------\\n\"); if (addr->return_filename) break; addr = addr->next; } fputc('\\n', f); \/* Now copy the file *\/ if (!(fm = Ufopen(addr->return_filename, \"rb\"))) fprintf(f, \" +++ Exim error... failed to open text file: %s\\n\", strerror(errno)); else { while ((ch = fgetc(fm)) != EOF) fputc(ch, f); (void)fclose(fm); } Uunlink(addr->return_filename); \/* Can now add to handled chain, first fishing off the next address on the msgchain. *\/ nextaddr = addr->next; addr->next = handled_addr; handled_addr = topaddr; } fputc('\\n', f); } \/* output machine readable part *\/ #ifdef SUPPORT_I18N if (message_smtputf8) fprintf(f, \"--%s\\n\" \"Content-type: message\/global-delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); else #endif fprintf(f, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for (addr = handled_addr; addr; addr = addr->next) { host_item * hu; fprintf(f, \"Action: failed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 5.0.0\\n\", addr->address); if ((hu = addr->host_used) && hu->name) { const uschar * s; fprintf(f, \"Remote-MTA: dns; %s\\n\", hu->name); #ifdef EXPERIMENTAL_DSN_INFO if (hu->address) { uschar * p = hu->port == 25 ? US\"\" : string_sprintf(\":%d\", hu->port); fprintf(f, \"Remote-MTA: X-ip; [%s]%s\\n\", hu->address, p); } if ((s = addr->smtp_greeting) && *s) fprintf(f, \"X-Remote-MTA-smtp-greeting: X-str; %s\\n\", s); if ((s = addr->helo_response) && *s) fprintf(f, \"X-Remote-MTA-helo-response: X-str; %s\\n\", s); if ((s = addr->message) && *s) fprintf(f, \"X-Exim-Diagnostic: X-str; %s\\n\", s); #endif print_dsn_diagnostic_code(addr, f); } fputc('\\n', f); } \/* Now copy the message, trying to give an intelligible comment if it is too long for it all to be copied. The limit isn't strictly applied because of the buffering. There is, however, an option to suppress copying altogether. *\/ emf_text = next_emf(emf, US\"copy\"); \/* add message body we ignore the intro text from template and add the text for bounce_return_size_limit at the end. bounce_return_message is ignored in case RET= is defined we honor these values otherwise bounce_return_body is honored. bounce_return_size_limit is always honored. *\/ fprintf(f, \"--%s\\n\", bound); dsnlimitmsg = US\"X-Exim-DSN-Information: Due to administrative limits only headers are returned\"; dsnnotifyhdr = NULL; topt = topt_add_return_path; \/* RET=HDRS? top priority *\/ if (dsn_ret == dsn_ret_hdrs) topt |= topt_no_body; else { struct stat statbuf; \/* no full body return at all? *\/ if (!bounce_return_body) { topt |= topt_no_body; \/* add header if we overrule RET=FULL *\/ if (dsn_ret == dsn_ret_full) dsnnotifyhdr = dsnlimitmsg; } \/* line length limited... return headers only if oversize *\/ \/* size limited ... return headers only if limit reached *\/ else if ( max_received_linelength > bounce_return_linesize_limit || ( bounce_return_size_limit > 0 && fstat(deliver_datafile, &statbuf) == 0 && statbuf.st_size > max ) ) { topt |= topt_no_body; dsnnotifyhdr = dsnlimitmsg; } } #ifdef SUPPORT_I18N if (message_smtputf8) fputs(topt & topt_no_body ? \"Content-type: message\/global-headers\\n\\n\" : \"Content-type: message\/global\\n\\n\", f); else #endif fputs(topt & topt_no_body ? \"Content-type: text\/rfc822-headers\\n\\n\" : \"Content-type: message\/rfc822\\n\\n\", f); fflush(f); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ { \/* Dummy transport for headers add *\/ transport_ctx tctx = {{0}}; transport_instance tb = {0}; tctx.u.fd = fileno(f); tctx.tblock = &tb; tctx.options = topt; tb.add_headers = dsnnotifyhdr; transport_write_message(&tctx, 0); } fflush(f); \/* we never add the final text. close the file *\/ if (emf) (void)fclose(emf); fprintf(f, \"\\n--%s--\\n\", bound); \/* Close the file, which should send an EOF to the child process that is receiving the message. Wait for it to finish. *\/ (void)fclose(f); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ \/* In the test harness, let the child do it's thing first. *\/ if (running_in_test_harness) millisleep(500); \/* If the process failed, there was some disaster in setting up the error message. Unless the message is very old, ensure that addr_defer is non-null, which will have the effect of leaving the message on the spool. The failed addresses will get tried again next time. However, we don't really want this to happen too often, so freeze the message unless there are some genuine deferred addresses to try. To do this we have to call spool_write_header() here, because with no genuine deferred addresses the normal code below doesn't get run. *\/ if (rc != 0) { uschar *s = US\"\"; if (now - received_time.tv_sec < retry_maximum_timeout && !addr_defer) { addr_defer = (address_item *)(+1); deliver_freeze = TRUE; deliver_frozen_at = time(NULL); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); s = US\" (frozen)\"; } deliver_msglog(\"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); log_write(0, LOG_MAIN, \"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); } \/* The message succeeded. Ensure that the recipients that failed are now marked finished with on the spool and their parents updated. *\/ else { for (addr = handled_addr; addr; addr = addr->next) { address_done(addr, logtod); child_done(addr, logtod); } \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } } } } disable_logging = FALSE; \/* In case left set *\/ \/* Come here from the mua_wrapper case if routing goes wrong *\/ DELIVERY_TIDYUP: \/* If there are now no deferred addresses, we are done. Preserve the message log if so configured, and we are using them. Otherwise, sling it. Then delete the message itself. *\/ if (!addr_defer) { uschar * fname; if (message_logs) { fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); if (preserve_message_logs) { int rc; uschar * moname = spool_fname(US\"msglog.OLD\", US\"\", id, US\"\"); if ((rc = Urename(fname, moname)) < 0) { (void)directory_make(spool_directory, spool_sname(US\"msglog.OLD\", US\"\"), MSGLOG_DIRECTORY_MODE, TRUE); rc = Urename(fname, moname); } if (rc < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to move %s to the \" \"msglog.OLD directory\", fname); } else if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); } \/* Remove the two message files. *\/ fname = spool_fname(US\"input\", message_subdir, id, US\"-D\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); fname = spool_fname(US\"input\", message_subdir, id, US\"-H\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Log the end of this message, with queue time if requested. *\/ if (LOGGING(queue_time_overall)) log_write(0, LOG_MAIN, \"Completed QT=%s\", string_timesince(&received_time)); else log_write(0, LOG_MAIN, \"Completed\"); \/* Unset deliver_freeze so that we won't try to move the spool files further down *\/ deliver_freeze = FALSE; #ifndef DISABLE_EVENT (void) event_raise(event_action, US\"msg:complete\", NULL); #endif } \/* If there are deferred addresses, we are keeping this message because it is not yet completed. Lose any temporary files that were catching output from pipes for any of the deferred addresses, handle one-time aliases, and see if the message has been on the queue for so long that it is time to send a warning message to the sender, unless it is a mailer-daemon. If all deferred addresses have the same domain, we can set deliver_domain for the expansion of delay_warning_ condition - if any of them are pipes, files, or autoreplies, use the parent's domain. If all the deferred addresses have an error number that indicates \"retry time not reached\", skip sending the warning message, because it won't contain the reason for the delay. It will get sent at the next real delivery attempt. However, if at least one address has tried, we'd better include all of them in the message. If we can't make a process to send the message, don't worry. For mailing list expansions we want to send the warning message to the mailing list manager. We can't do a perfect job here, as some addresses may have different errors addresses, but if we take the errors address from each deferred address it will probably be right in most cases. If addr_defer == +1, it means there was a problem sending an error message for failed addresses, and there were no \"real\" deferred addresses. The value was set just to keep the message on the spool, so there is nothing to do here. *\/ else if (addr_defer != (address_item *)(+1)) { address_item *addr; uschar *recipients = US\"\"; BOOL delivery_attempted = FALSE; deliver_domain = testflag(addr_defer, af_pfr) ? addr_defer->parent->domain : addr_defer->domain; for (addr = addr_defer; addr; addr = addr->next) { address_item *otaddr; if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE; if (deliver_domain) { const uschar *d = testflag(addr, af_pfr) ? addr->parent->domain : addr->domain; \/* The domain may be unset for an address that has never been routed because the system filter froze the message. *\/ if (!d || Ustrcmp(d, deliver_domain) != 0) deliver_domain = NULL; } if (addr->return_filename) Uunlink(addr->return_filename); \/* Handle the case of one-time aliases. If any address in the ancestry of this one is flagged, ensure it is in the recipients list, suitably flagged, and that its parent is marked delivered. *\/ for (otaddr = addr; otaddr; otaddr = otaddr->parent) if (otaddr->onetime_parent) break; if (otaddr) { int i; int t = recipients_count; for (i = 0; i < recipients_count; i++) { uschar *r = recipients_list[i].address; if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i; if (Ustrcmp(otaddr->address, r) == 0) break; } \/* Didn't find the address already in the list, and did find the ultimate parent's address in the list, and they really are different (i.e. not from an identity-redirect). After adding the recipient, update the errors address in the recipients list. *\/ if ( i >= recipients_count && t < recipients_count && Ustrcmp(otaddr->address, otaddr->parent->address) != 0) { DEBUG(D_deliver) debug_printf(\"one_time: adding %s in place of %s\\n\", otaddr->address, otaddr->parent->address); receive_add_recipient(otaddr->address, t); recipients_list[recipients_count-1].errors_to = otaddr->prop.errors_address; tree_add_nonrecipient(otaddr->parent->address); update_spool = TRUE; } } \/* Except for error messages, ensure that either the errors address for this deferred address or, if there is none, the sender address, is on the list of recipients for a warning message. *\/ if (sender_address[0]) { uschar * s = addr->prop.errors_address; if (!s) s = sender_address; if (Ustrstr(recipients, s) == NULL) recipients = string_sprintf(\"%s%s%s\", recipients, recipients[0] ? \",\" : \"\", s); } } \/* Send a warning message if the conditions are right. If the condition check fails because of a lookup defer, there is nothing we can do. The warning is not sent. Another attempt will be made at the next delivery attempt (if it also defers). *\/ if ( !queue_2stage && delivery_attempted && ( ((addr_defer->dsn_flags & rf_dsnflags) == 0) || (addr_defer->dsn_flags & rf_notify_delay) == rf_notify_delay ) && delay_warning[1] > 0 && sender_address[0] != 0 && ( !delay_warning_condition || expand_check_condition(delay_warning_condition, US\"delay_warning\", US\"option\") ) ) { int count; int show_time; int queue_time = time(NULL) - received_time.tv_sec; \/* When running in the test harness, there's an option that allows us to fudge this time so as to get repeatability of the tests. Take the first time off the list. In queue runs, the list pointer gets updated in the calling process. *\/ if (running_in_test_harness && fudged_queue_times[0] != 0) { int qt = readconf_readtime(fudged_queue_times, '\/', FALSE); if (qt >= 0) { DEBUG(D_deliver) debug_printf(\"fudged queue_times = %s\\n\", fudged_queue_times); queue_time = qt; } } \/* See how many warnings we should have sent by now *\/ for (count = 0; count < delay_warning[1]; count++) if (queue_time < delay_warning[count+2]) break; show_time = delay_warning[count+1]; if (count >= delay_warning[1]) { int extra; int last_gap = show_time; if (count > 1) last_gap -= delay_warning[count]; extra = (queue_time - delay_warning[count+1])\/last_gap; show_time += last_gap * extra; count += extra; } DEBUG(D_deliver) { debug_printf(\"time on queue = %s\\n\", readconf_printtime(queue_time)); debug_printf(\"warning counts: required %d done %d\\n\", count, warning_count); } \/* We have computed the number of warnings there should have been by now. If there haven't been enough, send one, and up the count to what it should have been. *\/ if (warning_count < count) { header_line *h; int fd; pid_t pid = child_open_exim(&fd); if (pid > 0) { uschar *wmf_text; FILE *wmf = NULL; FILE *f = fdopen(fd, \"wb\"); uschar * bound; transport_ctx tctx = {{0}}; if (warn_message_file) if (!(wmf = Ufopen(warn_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for warning \" \"message texts: %s\", warn_message_file, strerror(errno)); warnmsg_recipients = recipients; warnmsg_delay = queue_time < 120*60 ? string_sprintf(\"%d minutes\", show_time\/60) : string_sprintf(\"%d hours\", show_time\/3600); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(f); fprintf(f, \"To: %s\\n\", recipients); \/* generated boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(f, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); if ((wmf_text = next_emf(wmf, US\"header\"))) fprintf(f, \"%s\\n\", wmf_text); else fprintf(f, \"Subject: Warning: message %s delayed %s\\n\\n\", message_id, warnmsg_delay); \/* output human readable part as text\/plain section *\/ fprintf(f, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((wmf_text = next_emf(wmf, US\"intro\"))) fprintf(f, \"%s\", CS wmf_text); else { fprintf(f, \"This message was created automatically by mail delivery software.\\n\"); if (Ustrcmp(recipients, sender_address) == 0) fprintf(f, \"A message that you sent has not yet been delivered to one or more of its\\n\" \"recipients after more than \"); else fprintf(f, \"A message sent by\\n\\n <%s>\\n\\n\" \"has not yet been delivered to one or more of its recipients after more than \\n\", sender_address); fprintf(f, \"%s on the queue on %s.\\n\\n\" \"The message identifier is: %s\\n\", warnmsg_delay, primary_hostname, message_id); for (h = header_list; h; h = h->next) if (strncmpic(h->text, US\"Subject:\", 8) == 0) fprintf(f, \"The subject of the message is: %s\", h->text + 9); else if (strncmpic(h->text, US\"Date:\", 5) == 0) fprintf(f, \"The date of the message is: %s\", h->text + 6); fputc('\\n', f); fprintf(f, \"The address%s to which the message has not yet been \" \"delivered %s:\\n\", !addr_defer->next ? \"\" : \"es\", !addr_defer->next ? \"is\": \"are\"); } \/* List the addresses, with error information if allowed *\/ \/* store addr_defer for machine readable part *\/ address_item *addr_dsndefer = addr_defer; fputc('\\n', f); while (addr_defer) { address_item *addr = addr_defer; addr_defer = addr->next; if (print_address_information(addr, f, US\" \", US\"\\n \", US\"\")) print_address_error(addr, f, US\"Delay reason: \"); fputc('\\n', f); } fputc('\\n', f); \/* Final text *\/ if (wmf) { if ((wmf_text = next_emf(wmf, US\"final\"))) fprintf(f, \"%s\", CS wmf_text); (void)fclose(wmf); } else { fprintf(f, \"No action is required on your part. Delivery attempts will continue for\\n\" \"some time, and this warning may be repeated at intervals if the message\\n\" \"remains undelivered. Eventually the mail delivery software will give up,\\n\" \"and when that happens, the message will be returned to you.\\n\"); } \/* output machine readable part *\/ fprintf(f, \"\\n--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f,\"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f,\"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for ( ; addr_dsndefer; addr_dsndefer = addr_dsndefer->next) { if (addr_dsndefer->dsn_orcpt) fprintf(f, \"Original-Recipient: %s\\n\", addr_dsndefer->dsn_orcpt); fprintf(f, \"Action: delayed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 4.0.0\\n\", addr_dsndefer->address); if (addr_dsndefer->host_used && addr_dsndefer->host_used->name) { fprintf(f, \"Remote-MTA: dns; %s\\n\", addr_dsndefer->host_used->name); print_dsn_diagnostic_code(addr_dsndefer, f); } fputc('\\n', f); } fprintf(f, \"--%s\\n\" \"Content-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); \/* Close and wait for child process to complete, without a timeout. If there's an error, don't update the count. *\/ (void)fclose(f); if (child_close(pid, 0) == 0) { warning_count = count; update_spool = TRUE; \/* Ensure spool rewritten *\/ } } } } \/* Clear deliver_domain *\/ deliver_domain = NULL; \/* If this was a first delivery attempt, unset the first time flag, and ensure that the spool gets updated. *\/ if (deliver_firsttime) { deliver_firsttime = FALSE; update_spool = TRUE; } \/* If delivery was frozen and freeze_tell is set, generate an appropriate message, unless the message is a local error message (to avoid loops). Then log the freezing. If the text in \"frozen_info\" came from a system filter, it has been escaped into printing characters so as not to mess up log lines. For the \"tell\" message, we turn \\n back into newline. Also, insert a newline near the start instead of the \": \" string. *\/ if (deliver_freeze) { if (freeze_tell && freeze_tell[0] != 0 && !local_error_message) { uschar *s = string_copy(frozen_info); uschar *ss = Ustrstr(s, \" by the system filter: \"); if (ss != NULL) { ss[21] = '.'; ss[22] = '\\n'; } ss = s; while (*ss != 0) { if (*ss == '\\\\' && ss[1] == 'n') { *ss++ = ' '; *ss++ = '\\n'; } else ss++; } moan_tell_someone(freeze_tell, addr_defer, US\"Message frozen\", \"Message %s has been frozen%s.\\nThe sender is <%s>.\\n\", message_id, s, sender_address); } \/* Log freezing just before we update the -H file, to minimize the chance of a race problem. *\/ deliver_msglog(\"*** Frozen%s\\n\", frozen_info); log_write(0, LOG_MAIN, \"Frozen%s\", frozen_info); } \/* If there have been any updates to the non-recipients list, or other things that get written to the spool, we must now update the spool header file so that it has the right information for the next delivery attempt. If there was more than one address being delivered, the header_change update is done earlier, in case one succeeds and then something crashes. *\/ DEBUG(D_deliver) debug_printf(\"delivery deferred: update_spool=%d header_rewritten=%d\\n\", update_spool, header_rewritten); if (update_spool || header_rewritten) \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Finished with the message log. If the message is complete, it will have been unlinked or renamed above. *\/ if (message_logs) (void)fclose(message_log); \/* Now we can close and remove the journal file. Its only purpose is to record successfully completed deliveries asap so that this information doesn't get lost if Exim (or the machine) crashes. Forgetting about a failed delivery is not serious, as trying it again is not harmful. The journal might not be open if all addresses were deferred at routing or directing. Nevertheless, we must remove it if it exists (may have been lying around from a crash during the previous delivery attempt). We don't remove the journal if a delivery subprocess failed to pass back delivery information; this is controlled by the remove_journal flag. When the journal is left, we also don't move the message off the main spool if frozen and the option is set. It should get moved at the next attempt, after the journal has been inspected. *\/ if (journal_fd >= 0) (void)close(journal_fd); if (remove_journal) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if (Uunlink(fname) < 0 && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Move the message off the spool if requested *\/ #ifdef SUPPORT_MOVE_FROZEN_MESSAGES if (deliver_freeze && move_frozen_messages) (void)spool_move_message(id, message_subdir, US\"\", US\"F\"); #endif } \/* Closing the data file frees the lock; if the file has been unlinked it will go away. Otherwise the message becomes available for another process to try delivery. *\/ (void)close(deliver_datafile); deliver_datafile = -1; DEBUG(D_deliver) debug_printf(\"end delivery of %s\\n\", id); \/* It is unlikely that there will be any cached resources, since they are released after routing, and in the delivery subprocesses. However, it's possible for an expansion for something afterwards (for example, expand_check_condition) to do a lookup. We must therefore be sure everything is released. *\/ search_tidyup(); acl_where = ACL_WHERE_UNKNOWN; return final_yield; }","output":{"is_vulnerable":"True","vulnerability_types":["Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"],"explanation":"A flaw was found in Exim versions 4.87 to 4.91 (inclusive). Improper validation of recipient address in deliver_message() function in \/src\/deliver.c may lead to remote command execution.","severity_level":"NoInfo","cwe":"CWE-78","cve":"CVE-2019-10149"}} -{"idx":161338,"input":"static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define CFormat \"\/Filter [ \/%s ]\\n\" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \\ { \\ if (xref != (MagickOffsetType *) NULL) \\ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \\ ThrowWriterException((exception),(message)); \\ } DisableMSCWarning(4310) static const char XMPProfile[]= { \"\\n\" \"\\n\" \" \\n\" \" \\n\" \" %s<\/xap:ModifyDate>\\n\" \" %s<\/xap:CreateDate>\\n\" \" %s<\/xap:MetadataDate>\\n\" \" %s<\/xap:CreatorTool>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" application\/pdf<\/dc:format>\\n\" \" \\n\" \" \\n\" \" %s<\/rdf:li>\\n\" \" <\/rdf:Alt>\\n\" \" <\/dc:title>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf<\/xapMM:DocumentID>\\n\" \" uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb<\/xapMM:InstanceID>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" %s<\/pdf:Producer>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" 3<\/pdfaid:part>\\n\" \" B<\/pdfaid:conformance>\\n\" \" <\/rdf:Description>\\n\" \" <\/rdf:RDF>\\n\" \"<\/x:xmpmeta>\\n\" \"\\n\" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MagickPathExtent], buffer[MagickPathExtent], *escape, date[MagickPathExtent], **labels, page_geometry[MagickPathExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm local_time; time_t seconds; unsigned char *pixels; \/* Open output image file. *\/ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); \/* Allocate X ref memory. *\/ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(xref,0,2048UL*sizeof(*xref)); \/* Write Info object. *\/ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->alpha_trait != UndefinedPixelTrait) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,\"icc\"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\\n'); } \/* Write Catalog object. *\/ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Pages %.20g 0 R\\n\", (double) object+1); else { (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Metadata %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Pages %.20g 0 R\\n\", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Type \/Catalog\"); option=GetImageOption(image_info,\"pdf:page-direction\"); if ((option != (const char *) NULL) && (LocaleCompare(option,\"right-to-left\") == 0)) (void) WriteBlobString(image,\"\/ViewerPreferences<<\/PageDirection\/R2L>>\\n\"); (void) WriteBlobString(image,\"\\n\"); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { char create_date[MagickPathExtent], modify_date[MagickPathExtent], timestamp[MagickPathExtent], *url, xmp_profile[MagickPathExtent]; \/* Write XMP object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Subtype \/XML\\n\"); *modify_date='\\0'; value=GetImageProperty(image,\"date:modify\",exception); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MagickPathExtent); *create_date='\\0'; value=GetImageProperty(image,\"date:create\",exception); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MagickPathExtent); (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g\\n\", (double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Type \/Metadata\\n\"); (void) WriteBlobString(image,\">>\\nstream\\n\"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); } \/* Write Pages object. *\/ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/Pages\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Kids [ %.20g 0 R \", (double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; \/* Predict page object id's. *\/ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,\"icc\"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } (void) WriteBlobString(image,\"]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Count %.20g\\n\",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,\"icc\"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,exception) == MagickFalse) || (image->alpha_trait != UndefinedPixelTrait)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; \/* LZW compression is forbidden *\/ break; } case NoCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; \/* ASCII 85 compression is forbidden *\/ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Scale relative to dots-per-inch. *\/ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)\/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)\/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,\"PDF\") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry, MagickPathExtent); (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)\/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)\/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; \/* Write Page object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/Page\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Parent %.20g 0 R\\n\", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Resources <<\\n\"); labels=(char **) NULL; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent, \"\/Font << \/F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent, \"\/XObject << \/Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ProcSet %.20g 0 R >>\\n\", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width\/resolution.x, 72.0*media_info.height\/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/CropBox [0 0 %g %g]\\n\",72.0*media_info.width\/resolution.x, 72.0*media_info.height\/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Contents %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Thumb %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Contents object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); (void) WriteBlobString(image,\"q\\n\"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,\"BT\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/F%.20g %g Tf\\n\", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\", labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"ET\\n\"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MagickPathExtent, \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x, (double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Im%.20g Do\\n\",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"Q\\n\"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Procset object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageC\",MagickPathExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageB\",MagickPathExtent); else (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageI\",MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\" ]\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Font object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (labels != (char **) NULL) { (void) WriteBlobString(image,\"\/Type \/Font\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Type1\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/F%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/BaseFont \/Helvetica\\n\"); (void) WriteBlobString(image,\"\/Encoding \/MacRomanEncoding\\n\"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write XObject object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/XObject\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/Im%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"\/Filter [ \/CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/DecodeParms [ << \" \"\/K %s \/BlackIs1 false \/Columns %.20g \/Rows %.20g >> ]\\n\",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ColorSpace %.20g 0 R\\n\", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->alpha_trait != UndefinedPixelTrait) { (void) FormatLocaleString(buffer,MagickPathExtent,\"\/SMask %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runoffset encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed DirectColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { \/* Dump number of colors and colormap. *\/ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Colorspace object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); device=\"DeviceRGB\"; channels=0; if (image->colorspace == CMYKColorspace) { device=\"DeviceCMYK\"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { device=\"DeviceGray\"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device=\"DeviceRGB\"; channels=3; } profile=GetImageProfile(image,\"icc\"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"\/%s\\n\",device); else (void) FormatLocaleString(buffer,MagickPathExtent, \"[ \/Indexed \/%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; \/* Write ICC profile. *\/ (void) FormatLocaleString(buffer,MagickPathExtent, \"[\/ICCBased %.20g 0 R]\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n\/N %.20g\\n\" \"\/Filter \/ASCII85Decode\\n\/Length %.20g 0 R\\n\/Alternate \/%s\\n>>\\n\" \"stream\\n\",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"endstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Thumb object. *\/ SetGeometry(image,&geometry); (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception); if (tile_image == (Image *) NULL) return(MagickFalse); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"\/Filter [ \/CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/DecodeParms [ << \" \"\/K %s \/BlackIs1 false \/Columns %.20g \/Rows %.20g >> ]\\n\",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ColorSpace %.20g 0 R\\n\", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image, exception); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( tile_image,p))); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed DirectColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(tile_image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(tile_image,p))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } else { \/* Dump number of colors and colormap. *\/ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, \"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=(unsigned char) GetPixelIndex(tile_image,p); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(tile_image,p)); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,\">>\\n\"); else { \/* Write Colormap object. *\/ if (compression == NoCompression) (void) WriteBlobString(image,\"\/Filter [ \/ASCII85Decode ]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); continue; } (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write softmask object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (image->alpha_trait == UndefinedPixelTrait) (void) WriteBlobString(image,\">>\\n\"); else { (void) WriteBlobString(image,\"\/Type \/XObject\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/Ma%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\", (double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/ColorSpace \/DeviceGray\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/BitsPerComponent %d\\n\",(compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); \/* Write Metadata object. *\/ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Title (%s)\\n\", EscapeParenthesis(basename)); else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Title (\\xfe\\xff\"); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) length; i++) (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]); (void) FormatLocaleString(buffer,MagickPathExtent,\")\\n\"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&seconds,&local_time); #else (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time)); #endif (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\", local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday, local_time.tm_hour,local_time.tm_min,local_time.tm_sec); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/CreationDate (%s)\\n\", date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ModDate (%s)\\n\",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Producer (%s)\\n\",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Xref object. *\/ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,\"xref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"0000000000 65535 f \\n\"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"trailer\\n\"); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Size %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Info %.20g 0 R\\n\",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Root %.20g 0 R\\n\",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image,exception); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ID [<%s> <%s>]\\n\", GetImageProperty(image,\"signature\",exception), GetImageProperty(image,\"signature\",exception)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"startxref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"%%EOF\\n\"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":184520,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MaxTextExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False when converting or mogrifying *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; \/* Skip nominal layer count, frame count, and play time *\/ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\", \"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, \"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (*p && ((p-chunk) < (ssize_t) length)) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters \", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { \/* Interpolate *\/ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))\/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ else { \/* Interpolate *\/ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":269925,"input":"CallResult Interpreter::interpretFunction( Runtime *runtime, InterpreterState &state) { \/\/ The interepter is re-entrant and also saves\/restores its IP via the runtime \/\/ whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure \/\/ to preserve the IP across calls to interpeterFunction() disrupt interpreter \/\/ calls further up the C++ callstack. The RAII utility class below makes sure \/\/ we always do this correctly. \/\/ \/\/ TODO: The IPs stored in the C++ callstack via this holder will generally be \/\/ the same as in the JS stack frames via the Saved IP field. We can probably \/\/ get rid of one of these redundant stores. Doing this isn't completely \/\/ trivial as there are currently cases where we re-enter the interpreter \/\/ without calling Runtime::saveCallerIPInStackFrame(), and there are features \/\/ (I think mostly the debugger + stack traces) which implicitly rely on \/\/ this behavior. At least their tests break if this behavior is not \/\/ preserved. struct IPSaver { IPSaver(Runtime *runtime) : ip_(runtime->getCurrentIP()), runtime_(runtime) {} ~IPSaver() { runtime_->setCurrentIP(ip_); } private: const Inst *ip_; Runtime *runtime_; }; IPSaver ipSaver(runtime); #ifndef HERMES_ENABLE_DEBUGGER static_assert(!SingleStep, \"can't use single-step mode without the debugger\"); #endif \/\/ Make sure that the cache can use an optimization by avoiding a branch to \/\/ access the property storage. static_assert( HiddenClass::kDictionaryThreshold <= SegmentedArray::kValueToSegmentThreshold, \"Cannot avoid branches in cache check if the dictionary \" \"crossover point is larger than the inline storage\"); CodeBlock *curCodeBlock = state.codeBlock; const Inst *ip = nullptr; \/\/ Holds runtime->currentFrame_.ptr()-1 which is the first local \/\/ register. This eliminates the indirect load from Runtime and the -1 offset. PinnedHermesValue *frameRegs; \/\/ Strictness of current function. bool strictMode; \/\/ Default flags when accessing properties. PropOpFlags defaultPropOpFlags; \/\/ These CAPTURE_IP* macros should wrap around any major calls out of the \/\/ interpeter loop. They stash and retrieve the IP via the current Runtime \/\/ allowing the IP to be externally observed and even altered to change the flow \/\/ of execution. Explicitly saving AND restoring the IP from the Runtime in this \/\/ way means the C++ compiler will keep IP in a register within the rest of the \/\/ interpeter loop. \/\/ \/\/ When assertions are enabled we take the extra step of \"invalidating\" the IP \/\/ between captures so we can detect if it's erroneously accessed. \/\/ \/\/ In some cases we explicitly don't want to invalidate the IP and instead want \/\/ it to stay set. For this we use the *NO_INVALIDATE variants. This comes up \/\/ when we're performing a call operation which may re-enter the interpeter \/\/ loop, and so need the IP available for the saveCallerIPInStackFrame() call \/\/ when we next enter. #define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \\ runtime->setCurrentIP(ip); \\ dst = expr; \\ ip = runtime->getCurrentIP(); #ifdef NDEBUG #define CAPTURE_IP(expr) \\ runtime->setCurrentIP(ip); \\ (void)expr; \\ ip = runtime->getCurrentIP(); #define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) #else \/\/ !NDEBUG #define CAPTURE_IP(expr) \\ runtime->setCurrentIP(ip); \\ (void)expr; \\ ip = runtime->getCurrentIP(); \\ runtime->invalidateCurrentIP(); #define CAPTURE_IP_ASSIGN(dst, expr) \\ runtime->setCurrentIP(ip); \\ dst = expr; \\ ip = runtime->getCurrentIP(); \\ runtime->invalidateCurrentIP(); #endif \/\/ NDEBUG LLVM_DEBUG(dbgs() << \"interpretFunction() called\\n\"); ScopedNativeDepthTracker depthTracker{runtime}; if (LLVM_UNLIKELY(depthTracker.overflowed())) { return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); } if (!SingleStep) { if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) { return (*jitPtr)(runtime); } } GCScope gcScope(runtime); \/\/ Avoid allocating a handle dynamically by reusing this one. MutableHandle<> tmpHandle(runtime); CallResult res{ExecutionStatus::EXCEPTION}; CallResult> resPH{ExecutionStatus::EXCEPTION}; CallResult> resArgs{ExecutionStatus::EXCEPTION}; CallResult boolRes{ExecutionStatus::EXCEPTION}; \/\/ Mark the gcScope so we can clear all allocated handles. \/\/ Remember how many handles the scope has so we can clear them in the loop. static constexpr unsigned KEEP_HANDLES = 1; assert( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"scope has unexpected number of handles\"); INIT_OPCODE_PROFILER; #if !defined(HERMESVM_PROFILER_EXTERN) tailCall: #endif PROFILER_ENTER_FUNCTION(curCodeBlock); #ifdef HERMES_ENABLE_DEBUGGER runtime->getDebugger().willEnterCodeBlock(curCodeBlock); #endif runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock); \/\/ Update function executionCount_ count curCodeBlock->incrementExecutionCount(); if (!SingleStep) { auto newFrame = runtime->setCurrentFrameToTopOfStack(); runtime->saveCallerIPInStackFrame(); #ifndef NDEBUG runtime->invalidateCurrentIP(); #endif \/\/ Point frameRegs to the first register in the new frame. Note that at this \/\/ moment technically it points above the top of the stack, but we are never \/\/ going to access it. frameRegs = &newFrame.getFirstLocalRef(); #ifndef NDEBUG LLVM_DEBUG( dbgs() << \"function entry: stackLevel=\" << runtime->getStackLevel() << \", argCount=\" << runtime->getCurrentFrame().getArgCount() << \", frameSize=\" << curCodeBlock->getFrameSize() << \"\\n\"); LLVM_DEBUG( dbgs() << \" callee \" << DumpHermesValue( runtime->getCurrentFrame().getCalleeClosureOrCBRef()) << \"\\n\"); LLVM_DEBUG( dbgs() << \" this \" << DumpHermesValue(runtime->getCurrentFrame().getThisArgRef()) << \"\\n\"); for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) { LLVM_DEBUG( dbgs() << \" \" << llvh::format_decimal(i, 4) << \" \" << DumpHermesValue(runtime->getCurrentFrame().getArgRef(i)) << \"\\n\"); } #endif \/\/ Allocate the registers for the new frame. if (LLVM_UNLIKELY(!runtime->checkAndAllocStack( curCodeBlock->getFrameSize() + StackFrameLayout::CalleeExtraRegistersAtStart, HermesValue::encodeUndefinedValue()))) goto stackOverflow; ip = (Inst const *)curCodeBlock->begin(); \/\/ Check for invalid invocation. if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited( newFrame.isConstructorCall()))) { if (!newFrame.isConstructorCall()) { CAPTURE_IP( runtime->raiseTypeError(\"Class constructor invoked without new\")); } else { CAPTURE_IP(runtime->raiseTypeError(\"Function is not a constructor\")); } goto handleExceptionInParent; } } else { \/\/ Point frameRegs to the first register in the frame. frameRegs = &runtime->getCurrentFrame().getFirstLocalRef(); ip = (Inst const *)(curCodeBlock->begin() + state.offset); } assert((const uint8_t *)ip < curCodeBlock->end() && \"CodeBlock is empty\"); INIT_STATE_FOR_CODEBLOCK(curCodeBlock); #define BEFORE_OP_CODE \\ { \\ UPDATE_OPCODE_TIME_SPENT; \\ HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \\ HERMES_SLOW_ASSERT( \\ gcScope.getHandleCountDbg() == KEEP_HANDLES && \\ \"unaccounted handles were created\"); \\ HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && \"tmpHandle not cleared\"); \\ RECORD_OPCODE_START_TIME; \\ INC_OPCODE_COUNT; \\ } #ifdef HERMESVM_INDIRECT_THREADING static void *opcodeDispatch[] = { #define DEFINE_OPCODE(name) &&case_##name, #include \"hermes\/BCGen\/HBC\/BytecodeList.def\" &&case__last}; #define CASE(name) case_##name: #define DISPATCH \\ BEFORE_OP_CODE; \\ if (SingleStep) { \\ state.codeBlock = curCodeBlock; \\ state.offset = CUROFFSET; \\ return HermesValue::encodeUndefinedValue(); \\ } \\ goto *opcodeDispatch[(unsigned)ip->opCode] #else \/\/ HERMESVM_INDIRECT_THREADING #define CASE(name) case OpCode::name: #define DISPATCH \\ if (SingleStep) { \\ state.codeBlock = curCodeBlock; \\ state.offset = CUROFFSET; \\ return HermesValue::encodeUndefinedValue(); \\ } \\ continue #endif \/\/ HERMESVM_INDIRECT_THREADING #define RUN_DEBUGGER_ASYNC_BREAK(flags) \\ do { \\ CAPTURE_IP_ASSIGN( \\ auto dRes, \\ runDebuggerUpdatingState( \\ (uint8_t)(flags) & \\ (uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \\ ? Debugger::RunReason::AsyncBreakExplicit \\ : Debugger::RunReason::AsyncBreakImplicit, \\ runtime, \\ curCodeBlock, \\ ip, \\ frameRegs)); \\ if (dRes == ExecutionStatus::EXCEPTION) \\ goto exception; \\ } while (0) for (;;) { BEFORE_OP_CODE; #ifdef HERMESVM_INDIRECT_THREADING goto *opcodeDispatch[(unsigned)ip->opCode]; #else switch (ip->opCode) #endif { const Inst *nextIP; uint32_t idVal; bool tryProp; uint32_t callArgCount; \/\/ This is HermesValue::getRaw(), since HermesValue cannot be assigned \/\/ to. It is meant to be used only for very short durations, in the \/\/ dispatch of call instructions, when there is definitely no possibility \/\/ of a GC. HermesValue::RawType callNewTarget; \/\/\/ Handle an opcode \\p name with an out-of-line implementation in a function \/\/\/ ExecutionStatus caseName( \/\/\/ Runtime *, \/\/\/ PinnedHermesValue *frameRegs, \/\/\/ Inst *ip) #define CASE_OUTOFLINE(name) \\ CASE(name) { \\ CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \\ if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \\ goto exception; \\ } \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a binary arithmetic instruction with a fast path where both \/\/\/ operands are numbers. \/\/\/ \\param name the name of the instruction. The fast path case will have a \/\/\/ \"n\" appended to the name. \/\/\/ \\param oper the C++ operator to use to actually perform the arithmetic \/\/\/ operation. #define BINOP(name, oper) \\ CASE(name) { \\ if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\ \/* Fast-path. *\/ \\ CASE(name##N) { \\ O1REG(name) = HermesValue::encodeDoubleValue( \\ oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \\ } \\ CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) \\ goto exception; \\ double left = res->getDouble(); \\ CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) \\ goto exception; \\ O1REG(name) = \\ HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a shift instruction with a fast path where both \/\/\/ operands are numbers. \/\/\/ \\param name the name of the instruction. \/\/\/ \\param oper the C++ operator to use to actually perform the shift \/\/\/ operation. \/\/\/ \\param lConv the conversion function for the LHS of the expression. \/\/\/ \\param lType the type of the LHS operand. \/\/\/ \\param returnType the type of the return value. #define SHIFTOP(name, oper, lConv, lType, returnType) \\ CASE(name) { \\ if (LLVM_LIKELY( \\ O2REG(name).isNumber() && \\ O3REG(name).isNumber())) { \/* Fast-path. *\/ \\ auto lnum = static_cast( \\ hermes::truncateToInt32(O2REG(name).getNumber())); \\ auto rnum = static_cast( \\ hermes::truncateToInt32(O3REG(name).getNumber())) & \\ 0x1f; \\ O1REG(name) = HermesValue::encodeDoubleValue( \\ static_cast(lnum oper rnum)); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \\ CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ auto lnum = static_cast(res->getNumber()); \\ CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ auto rnum = static_cast(res->getNumber()) & 0x1f; \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ O1REG(name) = HermesValue::encodeDoubleValue( \\ static_cast(lnum oper rnum)); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a binary bitwise instruction with a fast path where both \/\/\/ operands are numbers. \/\/\/ \\param name the name of the instruction. \/\/\/ \\param oper the C++ operator to use to actually perform the bitwise \/\/\/ operation. #define BITWISEBINOP(name, oper) \\ CASE(name) { \\ if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\ \/* Fast-path. *\/ \\ O1REG(name) = HermesValue::encodeDoubleValue( \\ hermes::truncateToInt32(O2REG(name).getNumber()) \\ oper hermes::truncateToInt32(O3REG(name).getNumber())); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \\ CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ int32_t left = res->getNumberAs(); \\ CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ O1REG(name) = \\ HermesValue::encodeNumberValue(left oper res->getNumberAs()); \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a comparison instruction. \/\/\/ \\param name the name of the instruction. \/\/\/ \\param oper the C++ operator to use to actually perform the fast arithmetic \/\/\/ comparison. \/\/\/ \\param operFuncName function to call for the slow-path comparison. #define CONDOP(name, oper, operFuncName) \\ CASE(name) { \\ if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\ \/* Fast-path. *\/ \\ O1REG(name) = HermesValue::encodeBoolValue( \\ O2REG(name).getNumber() oper O3REG(name).getNumber()); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \\ CAPTURE_IP_ASSIGN( \\ boolRes, \\ operFuncName( \\ runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \\ if (boolRes == ExecutionStatus::EXCEPTION) \\ goto exception; \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a comparison conditional jump with a fast path where both \/\/\/ operands are numbers. \/\/\/ \\param name the name of the instruction. The fast path case will have a \/\/\/ \"N\" appended to the name. \/\/\/ \\param suffix Optional suffix to be added to the end (e.g. Long) \/\/\/ \\param oper the C++ operator to use to actually perform the fast arithmetic \/\/\/ comparison. \/\/\/ \\param operFuncName function to call for the slow-path comparison. \/\/\/ \\param trueDest ip value if the conditional evaluates to true \/\/\/ \\param falseDest ip value if the conditional evaluates to false #define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \\ CASE(name##suffix) { \\ if (LLVM_LIKELY( \\ O2REG(name##suffix).isNumber() && \\ O3REG(name##suffix).isNumber())) { \\ \/* Fast-path. *\/ \\ CASE(name##N##suffix) { \\ if (O2REG(name##N##suffix) \\ .getNumber() oper O3REG(name##N##suffix) \\ .getNumber()) { \\ ip = trueDest; \\ DISPATCH; \\ } \\ ip = falseDest; \\ DISPATCH; \\ } \\ } \\ CAPTURE_IP_ASSIGN( \\ boolRes, \\ operFuncName( \\ runtime, \\ Handle<>(&O2REG(name##suffix)), \\ Handle<>(&O3REG(name##suffix)))); \\ if (boolRes == ExecutionStatus::EXCEPTION) \\ goto exception; \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ if (boolRes.getValue()) { \\ ip = trueDest; \\ DISPATCH; \\ } \\ ip = falseDest; \\ DISPATCH; \\ } \/\/\/ Implement a strict equality conditional jump \/\/\/ \\param name the name of the instruction. \/\/\/ \\param suffix Optional suffix to be added to the end (e.g. Long) \/\/\/ \\param trueDest ip value if the conditional evaluates to true \/\/\/ \\param falseDest ip value if the conditional evaluates to false #define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \\ CASE(name##suffix) { \\ if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \\ ip = trueDest; \\ DISPATCH; \\ } \\ ip = falseDest; \\ DISPATCH; \\ } \/\/\/ Implement an equality conditional jump \/\/\/ \\param name the name of the instruction. \/\/\/ \\param suffix Optional suffix to be added to the end (e.g. Long) \/\/\/ \\param trueDest ip value if the conditional evaluates to true \/\/\/ \\param falseDest ip value if the conditional evaluates to false #define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \\ CASE(name##suffix) { \\ CAPTURE_IP_ASSIGN( \\ res, \\ abstractEqualityTest_RJS( \\ runtime, \\ Handle<>(&O2REG(name##suffix)), \\ Handle<>(&O3REG(name##suffix)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ if (res->getBool()) { \\ ip = trueDest; \\ DISPATCH; \\ } \\ ip = falseDest; \\ DISPATCH; \\ } \/\/\/ Implement the long and short forms of a conditional jump, and its negation. #define JCOND(name, oper, operFuncName) \\ JCOND_IMPL( \\ J##name, \\ , \\ oper, \\ operFuncName, \\ IPADD(ip->iJ##name.op1), \\ NEXTINST(J##name)); \\ JCOND_IMPL( \\ J##name, \\ Long, \\ oper, \\ operFuncName, \\ IPADD(ip->iJ##name##Long.op1), \\ NEXTINST(J##name##Long)); \\ JCOND_IMPL( \\ JNot##name, \\ , \\ oper, \\ operFuncName, \\ NEXTINST(JNot##name), \\ IPADD(ip->iJNot##name.op1)); \\ JCOND_IMPL( \\ JNot##name, \\ Long, \\ oper, \\ operFuncName, \\ NEXTINST(JNot##name##Long), \\ IPADD(ip->iJNot##name##Long.op1)); \/\/\/ Load a constant. \/\/\/ \\param value is the value to store in the output register. #define LOAD_CONST(name, value) \\ CASE(name) { \\ O1REG(name) = value; \\ ip = NEXTINST(name); \\ DISPATCH; \\ } #define LOAD_CONST_CAPTURE_IP(name, value) \\ CASE(name) { \\ CAPTURE_IP_ASSIGN(O1REG(name), value); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } CASE(Mov) { O1REG(Mov) = O2REG(Mov); ip = NEXTINST(Mov); DISPATCH; } CASE(MovLong) { O1REG(MovLong) = O2REG(MovLong); ip = NEXTINST(MovLong); DISPATCH; } CASE(LoadParam) { if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) { \/\/ index 0 must load 'this'. Index 1 the first argument, etc. O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1); ip = NEXTINST(LoadParam); DISPATCH; } O1REG(LoadParam) = HermesValue::encodeUndefinedValue(); ip = NEXTINST(LoadParam); DISPATCH; } CASE(LoadParamLong) { if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) { \/\/ index 0 must load 'this'. Index 1 the first argument, etc. O1REG(LoadParamLong) = FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1); ip = NEXTINST(LoadParamLong); DISPATCH; } O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue(); ip = NEXTINST(LoadParamLong); DISPATCH; } CASE(CoerceThisNS) { if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) { O1REG(CoerceThisNS) = O2REG(CoerceThisNS); } else if ( O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) { O1REG(CoerceThisNS) = runtime->global_; } else { tmpHandle = O2REG(CoerceThisNS); nextIP = NEXTINST(CoerceThisNS); goto coerceThisSlowPath; } ip = NEXTINST(CoerceThisNS); DISPATCH; } CASE(LoadThisNS) { if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) { O1REG(LoadThisNS) = FRAME.getThisArgRef(); } else if ( FRAME.getThisArgRef().isNull() || FRAME.getThisArgRef().isUndefined()) { O1REG(LoadThisNS) = runtime->global_; } else { tmpHandle = FRAME.getThisArgRef(); nextIP = NEXTINST(LoadThisNS); goto coerceThisSlowPath; } ip = NEXTINST(LoadThisNS); DISPATCH; } coerceThisSlowPath : { CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle)); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CoerceThisNS) = res.getValue(); tmpHandle.clear(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(ConstructLong) { callArgCount = (uint32_t)ip->iConstructLong.op3; nextIP = NEXTINST(ConstructLong); callNewTarget = O2REG(ConstructLong).getRaw(); goto doCall; } CASE(CallLong) { callArgCount = (uint32_t)ip->iCallLong.op3; nextIP = NEXTINST(CallLong); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } \/\/ Note in Call1 through Call4, the first argument is 'this' which has \/\/ argument index -1. \/\/ Also note that we are writing to callNewTarget last, to avoid the \/\/ possibility of it being aliased by the arg writes. CASE(Call1) { callArgCount = 1; nextIP = NEXTINST(Call1); StackFramePtr fr{runtime->stackPointer_}; fr.getArgRefUnsafe(-1) = O3REG(Call1); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } CASE(Call2) { callArgCount = 2; nextIP = NEXTINST(Call2); StackFramePtr fr{runtime->stackPointer_}; fr.getArgRefUnsafe(-1) = O3REG(Call2); fr.getArgRefUnsafe(0) = O4REG(Call2); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } CASE(Call3) { callArgCount = 3; nextIP = NEXTINST(Call3); StackFramePtr fr{runtime->stackPointer_}; fr.getArgRefUnsafe(-1) = O3REG(Call3); fr.getArgRefUnsafe(0) = O4REG(Call3); fr.getArgRefUnsafe(1) = O5REG(Call3); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } CASE(Call4) { callArgCount = 4; nextIP = NEXTINST(Call4); StackFramePtr fr{runtime->stackPointer_}; fr.getArgRefUnsafe(-1) = O3REG(Call4); fr.getArgRefUnsafe(0) = O4REG(Call4); fr.getArgRefUnsafe(1) = O5REG(Call4); fr.getArgRefUnsafe(2) = O6REG(Call4); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } CASE(Construct) { callArgCount = (uint32_t)ip->iConstruct.op3; nextIP = NEXTINST(Construct); callNewTarget = O2REG(Construct).getRaw(); goto doCall; } CASE(Call) { callArgCount = (uint32_t)ip->iCall.op3; nextIP = NEXTINST(Call); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); \/\/ Fall through. } doCall : { #ifdef HERMES_ENABLE_DEBUGGER \/\/ Check for an async debugger request. if (uint8_t asyncFlags = runtime->testAndClearDebuggerAsyncBreakRequest()) { RUN_DEBUGGER_ASYNC_BREAK(asyncFlags); gcScope.flushToSmallCount(KEEP_HANDLES); DISPATCH; } #endif \/\/ Subtract 1 from callArgCount as 'this' is considered an argument in the \/\/ instruction, but not in the frame. CAPTURE_IP_ASSIGN_NO_INVALIDATE( auto newFrame, StackFramePtr::initFrame( runtime->stackPointer_, FRAME, ip, curCodeBlock, callArgCount - 1, O2REG(Call), HermesValue::fromRaw(callNewTarget))); (void)newFrame; SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame)); if (auto *func = dyn_vmcast(O2REG(Call))) { assert(!SingleStep && \"can't single-step a call\"); #ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES runtime->pushCallStack(curCodeBlock, ip); #endif CodeBlock *calleeBlock = func->getCodeBlock(); calleeBlock->lazyCompile(runtime); #if defined(HERMESVM_PROFILER_EXTERN) CAPTURE_IP_ASSIGN_NO_INVALIDATE( res, runtime->interpretFunction(calleeBlock)); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(Call) = *res; gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; #else if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) { res = (*jitPtr)(runtime); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) goto exception; O1REG(Call) = *res; SLOW_DEBUG( dbgs() << \"JIT return value r\" << (unsigned)ip->iCall.op1 << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\"); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } curCodeBlock = calleeBlock; goto tailCall; #endif } CAPTURE_IP_ASSIGN_NO_INVALIDATE( resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call))); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(Call) = std::move(resPH->get()); SLOW_DEBUG( dbgs() << \"native return value r\" << (unsigned)ip->iCall.op1 << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\"); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(CallDirect) CASE(CallDirectLongIndex) { #ifdef HERMES_ENABLE_DEBUGGER \/\/ Check for an async debugger request. if (uint8_t asyncFlags = runtime->testAndClearDebuggerAsyncBreakRequest()) { RUN_DEBUGGER_ASYNC_BREAK(asyncFlags); gcScope.flushToSmallCount(KEEP_HANDLES); DISPATCH; } #endif CAPTURE_IP_ASSIGN( CodeBlock * calleeBlock, ip->opCode == OpCode::CallDirect ? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate( ip->iCallDirect.op3) : curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate( ip->iCallDirectLongIndex.op3)); CAPTURE_IP_ASSIGN_NO_INVALIDATE( auto newFrame, StackFramePtr::initFrame( runtime->stackPointer_, FRAME, ip, curCodeBlock, (uint32_t)ip->iCallDirect.op2 - 1, HermesValue::encodeNativePointer(calleeBlock), HermesValue::encodeUndefinedValue())); (void)newFrame; LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame)); assert(!SingleStep && \"can't single-step a call\"); calleeBlock->lazyCompile(runtime); #if defined(HERMESVM_PROFILER_EXTERN) CAPTURE_IP_ASSIGN_NO_INVALIDATE( res, runtime->interpretFunction(calleeBlock)); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CallDirect) = *res; gcScope.flushToSmallCount(KEEP_HANDLES); ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect) : NEXTINST(CallDirectLongIndex); DISPATCH; #else if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) { res = (*jitPtr)(runtime); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) goto exception; O1REG(CallDirect) = *res; LLVM_DEBUG( dbgs() << \"JIT return value r\" << (unsigned)ip->iCallDirect.op1 << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\"); gcScope.flushToSmallCount(KEEP_HANDLES); ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect) : NEXTINST(CallDirectLongIndex); DISPATCH; } curCodeBlock = calleeBlock; goto tailCall; #endif } CASE(CallBuiltin) { NativeFunction *nf = runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2); CAPTURE_IP_ASSIGN( auto newFrame, StackFramePtr::initFrame( runtime->stackPointer_, FRAME, ip, curCodeBlock, (uint32_t)ip->iCallBuiltin.op3 - 1, nf, false)); \/\/ \"thisArg\" is implicitly assumed to \"undefined\". newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue(); SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame)); CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) goto exception; O1REG(CallBuiltin) = std::move(resPH->get()); SLOW_DEBUG( dbgs() << \"native return value r\" << (unsigned)ip->iCallBuiltin.op1 << \"=\" << DumpHermesValue(O1REG(CallBuiltin)) << \"\\n\"); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CallBuiltin); DISPATCH; } CASE(CompleteGenerator) { auto *innerFn = vmcast( runtime->getCurrentFrame().getCalleeClosure()); innerFn->setState(GeneratorInnerFunction::State::Completed); ip = NEXTINST(CompleteGenerator); DISPATCH; } CASE(SaveGenerator) { nextIP = IPADD(ip->iSaveGenerator.op1); goto doSaveGen; } CASE(SaveGeneratorLong) { nextIP = IPADD(ip->iSaveGeneratorLong.op1); goto doSaveGen; } doSaveGen : { auto *innerFn = vmcast( runtime->getCurrentFrame().getCalleeClosure()); innerFn->saveStack(runtime); innerFn->setNextIP(nextIP); innerFn->setState(GeneratorInnerFunction::State::SuspendedYield); ip = NEXTINST(SaveGenerator); DISPATCH; } CASE(StartGenerator) { auto *innerFn = vmcast( runtime->getCurrentFrame().getCalleeClosure()); if (innerFn->getState() == GeneratorInnerFunction::State::SuspendedStart) { nextIP = NEXTINST(StartGenerator); } else { nextIP = innerFn->getNextIP(); innerFn->restoreStack(runtime); } innerFn->setState(GeneratorInnerFunction::State::Executing); ip = nextIP; DISPATCH; } CASE(ResumeGenerator) { auto *innerFn = vmcast( runtime->getCurrentFrame().getCalleeClosure()); O1REG(ResumeGenerator) = innerFn->getResult(); O2REG(ResumeGenerator) = HermesValue::encodeBoolValue( innerFn->getAction() == GeneratorInnerFunction::Action::Return); innerFn->clearResult(runtime); if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) { runtime->setThrownValue(O1REG(ResumeGenerator)); goto exception; } ip = NEXTINST(ResumeGenerator); DISPATCH; } CASE(Ret) { #ifdef HERMES_ENABLE_DEBUGGER \/\/ Check for an async debugger request. if (uint8_t asyncFlags = runtime->testAndClearDebuggerAsyncBreakRequest()) { RUN_DEBUGGER_ASYNC_BREAK(asyncFlags); gcScope.flushToSmallCount(KEEP_HANDLES); DISPATCH; } #endif PROFILER_EXIT_FUNCTION(curCodeBlock); #ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES runtime->popCallStack(); #endif \/\/ Store the return value. res = O1REG(Ret); ip = FRAME.getSavedIP(); curCodeBlock = FRAME.getSavedCodeBlock(); frameRegs = &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef(); SLOW_DEBUG( dbgs() << \"function exit: restored stackLevel=\" << runtime->getStackLevel() << \"\\n\"); \/\/ Are we returning to native code? if (!curCodeBlock) { SLOW_DEBUG(dbgs() << \"function exit: returning to native code\\n\"); return res; } \/\/ Return because of recursive calling structure #if defined(HERMESVM_PROFILER_EXTERN) return res; #endif INIT_STATE_FOR_CODEBLOCK(curCodeBlock); O1REG(Call) = res.getValue(); ip = nextInstCall(ip); DISPATCH; } CASE(Catch) { assert(!runtime->thrownValue_.isEmpty() && \"Invalid thrown value\"); assert( !isUncatchableError(runtime->thrownValue_) && \"Uncatchable thrown value was caught\"); O1REG(Catch) = runtime->thrownValue_; runtime->clearThrownValue(); #ifdef HERMES_ENABLE_DEBUGGER \/\/ Signal to the debugger that we're done unwinding an exception, \/\/ and we can resume normal debugging flow. runtime->debugger_.finishedUnwindingException(); #endif ip = NEXTINST(Catch); DISPATCH; } CASE(Throw) { runtime->thrownValue_ = O1REG(Throw); SLOW_DEBUG( dbgs() << \"Exception thrown: \" << DumpHermesValue(runtime->thrownValue_) << \"\\n\"); goto exception; } CASE(ThrowIfUndefinedInst) { if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) { SLOW_DEBUG( dbgs() << \"Throwing ReferenceError for undefined variable\"); CAPTURE_IP(runtime->raiseReferenceError( \"accessing an uninitialized variable\")); goto exception; } ip = NEXTINST(ThrowIfUndefinedInst); DISPATCH; } CASE(Debugger) { SLOW_DEBUG(dbgs() << \"debugger statement executed\\n\"); #ifdef HERMES_ENABLE_DEBUGGER { if (!runtime->debugger_.isDebugging()) { \/\/ Only run the debugger if we're not already debugging. \/\/ Don't want to call it again and mess with its state. CAPTURE_IP_ASSIGN( auto res, runDebuggerUpdatingState( Debugger::RunReason::Opcode, runtime, curCodeBlock, ip, frameRegs)); if (res == ExecutionStatus::EXCEPTION) { \/\/ If one of the internal steps threw, \/\/ then handle that here by jumping to where we're supposed to go. \/\/ If we're in mid-step, the breakpoint at the catch point \/\/ will have been set by the debugger. \/\/ We don't want to execute this instruction because it's already \/\/ thrown. goto exception; } } auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip); if (breakpointOpt.hasValue()) { \/\/ We're on a breakpoint but we're supposed to continue. curCodeBlock->uninstallBreakpointAtOffset( CUROFFSET, breakpointOpt->opCode); if (ip->opCode == OpCode::Debugger) { \/\/ Breakpointed a debugger instruction, so move past it \/\/ since we've already called the debugger on this instruction. ip = NEXTINST(Debugger); } else { InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET}; CAPTURE_IP_ASSIGN( ExecutionStatus status, runtime->stepFunction(newState)); curCodeBlock->installBreakpointAtOffset(CUROFFSET); if (status == ExecutionStatus::EXCEPTION) { goto exception; } curCodeBlock = newState.codeBlock; ip = newState.codeBlock->getOffsetPtr(newState.offset); INIT_STATE_FOR_CODEBLOCK(curCodeBlock); \/\/ Single-stepping should handle call stack management for us. frameRegs = &runtime->getCurrentFrame().getFirstLocalRef(); } } else if (ip->opCode == OpCode::Debugger) { \/\/ No breakpoint here and we've already run the debugger, \/\/ just continue on. \/\/ If the current instruction is no longer a debugger instruction, \/\/ we're just going to keep executing from the current IP. ip = NEXTINST(Debugger); } gcScope.flushToSmallCount(KEEP_HANDLES); } DISPATCH; #else ip = NEXTINST(Debugger); DISPATCH; #endif } CASE(AsyncBreakCheck) { if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) { #ifdef HERMES_ENABLE_DEBUGGER if (uint8_t asyncFlags = runtime->testAndClearDebuggerAsyncBreakRequest()) { RUN_DEBUGGER_ASYNC_BREAK(asyncFlags); } #endif if (runtime->testAndClearTimeoutAsyncBreakRequest()) { CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout()); if (nRes == ExecutionStatus::EXCEPTION) { goto exception; } } } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(AsyncBreakCheck); DISPATCH; } CASE(ProfilePoint) { #ifdef HERMESVM_PROFILER_BB auto pointIndex = ip->iProfilePoint.op1; SLOW_DEBUG(llvh::dbgs() << \"ProfilePoint: \" << pointIndex << \"\\n\"); CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock( curCodeBlock, pointIndex)); #endif ip = NEXTINST(ProfilePoint); DISPATCH; } CASE(Unreachable) { llvm_unreachable(\"Hermes bug: unreachable instruction\"); } CASE(CreateClosure) { idVal = ip->iCreateClosure.op3; nextIP = NEXTINST(CreateClosure); goto createClosure; } CASE(CreateClosureLongIndex) { idVal = ip->iCreateClosureLongIndex.op3; nextIP = NEXTINST(CreateClosureLongIndex); goto createClosure; } createClosure : { auto *runtimeModule = curCodeBlock->getRuntimeModule(); CAPTURE_IP_ASSIGN( O1REG(CreateClosure), JSFunction::create( runtime, runtimeModule->getDomain(runtime), Handle::vmcast(&runtime->functionPrototype), Handle::vmcast(&O2REG(CreateClosure)), runtimeModule->getCodeBlockMayAllocate(idVal)) .getHermesValue()); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(CreateGeneratorClosure) { CAPTURE_IP_ASSIGN( auto res, createGeneratorClosure( runtime, curCodeBlock->getRuntimeModule(), ip->iCreateClosure.op3, Handle::vmcast(&O2REG(CreateGeneratorClosure)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CreateGeneratorClosure) = res->getHermesValue(); res->invalidate(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateGeneratorClosure); DISPATCH; } CASE(CreateGeneratorClosureLongIndex) { CAPTURE_IP_ASSIGN( auto res, createGeneratorClosure( runtime, curCodeBlock->getRuntimeModule(), ip->iCreateClosureLongIndex.op3, Handle::vmcast( &O2REG(CreateGeneratorClosureLongIndex)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue(); res->invalidate(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateGeneratorClosureLongIndex); DISPATCH; } CASE(CreateGenerator) { CAPTURE_IP_ASSIGN( auto res, createGenerator_RJS( runtime, curCodeBlock->getRuntimeModule(), ip->iCreateGenerator.op3, Handle::vmcast(&O2REG(CreateGenerator)), FRAME.getNativeArgs())); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CreateGenerator) = res->getHermesValue(); res->invalidate(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateGenerator); DISPATCH; } CASE(CreateGeneratorLongIndex) { CAPTURE_IP_ASSIGN( auto res, createGenerator_RJS( runtime, curCodeBlock->getRuntimeModule(), ip->iCreateGeneratorLongIndex.op3, Handle::vmcast(&O2REG(CreateGeneratorLongIndex)), FRAME.getNativeArgs())); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CreateGeneratorLongIndex) = res->getHermesValue(); res->invalidate(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateGeneratorLongIndex); DISPATCH; } CASE(GetEnvironment) { \/\/ The currently executing function must exist, so get the environment. Environment *curEnv = FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime); for (unsigned level = ip->iGetEnvironment.op2; level; --level) { assert(curEnv && \"invalid environment relative level\"); curEnv = curEnv->getParentEnvironment(runtime); } O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv); ip = NEXTINST(GetEnvironment); DISPATCH; } CASE(CreateEnvironment) { tmpHandle = HermesValue::encodeObjectValue( FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime)); CAPTURE_IP_ASSIGN( res, Environment::create( runtime, tmpHandle->getPointer() ? Handle::vmcast(tmpHandle) : Handle::vmcast_or_null( &runtime->nullPointer_), curCodeBlock->getEnvironmentSize())); if (res == ExecutionStatus::EXCEPTION) { goto exception; } O1REG(CreateEnvironment) = *res; #ifdef HERMES_ENABLE_DEBUGGER FRAME.getDebugEnvironmentRef() = *res; #endif tmpHandle = HermesValue::encodeUndefinedValue(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateEnvironment); DISPATCH; } CASE(StoreToEnvironment) { vmcast(O1REG(StoreToEnvironment)) ->slot(ip->iStoreToEnvironment.op2) .set(O3REG(StoreToEnvironment), &runtime->getHeap()); ip = NEXTINST(StoreToEnvironment); DISPATCH; } CASE(StoreToEnvironmentL) { vmcast(O1REG(StoreToEnvironmentL)) ->slot(ip->iStoreToEnvironmentL.op2) .set(O3REG(StoreToEnvironmentL), &runtime->getHeap()); ip = NEXTINST(StoreToEnvironmentL); DISPATCH; } CASE(StoreNPToEnvironment) { vmcast(O1REG(StoreNPToEnvironment)) ->slot(ip->iStoreNPToEnvironment.op2) .setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap()); ip = NEXTINST(StoreNPToEnvironment); DISPATCH; } CASE(StoreNPToEnvironmentL) { vmcast(O1REG(StoreNPToEnvironmentL)) ->slot(ip->iStoreNPToEnvironmentL.op2) .setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap()); ip = NEXTINST(StoreNPToEnvironmentL); DISPATCH; } CASE(LoadFromEnvironment) { O1REG(LoadFromEnvironment) = vmcast(O2REG(LoadFromEnvironment)) ->slot(ip->iLoadFromEnvironment.op3); ip = NEXTINST(LoadFromEnvironment); DISPATCH; } CASE(LoadFromEnvironmentL) { O1REG(LoadFromEnvironmentL) = vmcast(O2REG(LoadFromEnvironmentL)) ->slot(ip->iLoadFromEnvironmentL.op3); ip = NEXTINST(LoadFromEnvironmentL); DISPATCH; } CASE(GetGlobalObject) { O1REG(GetGlobalObject) = runtime->global_; ip = NEXTINST(GetGlobalObject); DISPATCH; } CASE(GetNewTarget) { O1REG(GetNewTarget) = FRAME.getNewTargetRef(); ip = NEXTINST(GetNewTarget); DISPATCH; } CASE(DeclareGlobalVar) { DefinePropertyFlags dpf = DefinePropertyFlags::getDefaultNewPropertyFlags(); dpf.configurable = 0; \/\/ Do not overwrite existing globals with undefined. dpf.setValue = 0; CAPTURE_IP_ASSIGN( auto res, JSObject::defineOwnProperty( runtime->getGlobal(), runtime, ID(ip->iDeclareGlobalVar.op1), dpf, Runtime::getUndefinedValue(), PropOpFlags().plusThrowOnError())); if (res == ExecutionStatus::EXCEPTION) { assert( !runtime->getGlobal()->isProxyObject() && \"global can't be a proxy object\"); \/\/ If the property already exists, this should be a noop. \/\/ Instead of incurring the cost to check every time, do it \/\/ only if an exception is thrown, and swallow the exception \/\/ if it exists, since we didn't want to make the call, \/\/ anyway. This most likely means the property is \/\/ non-configurable. NamedPropertyDescriptor desc; CAPTURE_IP_ASSIGN( auto res, JSObject::getOwnNamedDescriptor( runtime->getGlobal(), runtime, ID(ip->iDeclareGlobalVar.op1), desc)); if (!res) { goto exception; } else { runtime->clearThrownValue(); } \/\/ fall through } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(DeclareGlobalVar); DISPATCH; } CASE(TryGetByIdLong) { tryProp = true; idVal = ip->iTryGetByIdLong.op4; nextIP = NEXTINST(TryGetByIdLong); goto getById; } CASE(GetByIdLong) { tryProp = false; idVal = ip->iGetByIdLong.op4; nextIP = NEXTINST(GetByIdLong); goto getById; } CASE(GetByIdShort) { tryProp = false; idVal = ip->iGetByIdShort.op4; nextIP = NEXTINST(GetByIdShort); goto getById; } CASE(TryGetById) { tryProp = true; idVal = ip->iTryGetById.op4; nextIP = NEXTINST(TryGetById); goto getById; } CASE(GetById) { tryProp = false; idVal = ip->iGetById.op4; nextIP = NEXTINST(GetById); } getById : { ++NumGetById; \/\/ NOTE: it is safe to use OnREG(GetById) here because all instructions \/\/ have the same layout: opcode, registers, non-register operands, i.e. \/\/ they only differ in the width of the last \"identifier\" field. CallResult propRes{ExecutionStatus::EXCEPTION}; if (LLVM_LIKELY(O2REG(GetById).isObject())) { auto *obj = vmcast(O2REG(GetById)); auto cacheIdx = ip->iGetById.op3; auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx); #ifdef HERMESVM_PROFILER_BB { HERMES_SLOW_ASSERT( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"unaccounted handles were created\"); auto objHandle = runtime->makeHandle(obj); auto cacheHCPtr = vmcast_or_null(static_cast( cacheEntry->clazz.get(runtime, &runtime->getHeap()))); CAPTURE_IP(runtime->recordHiddenClass( curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr)); \/\/ obj may be moved by GC due to recordHiddenClass obj = objHandle.get(); } gcScope.flushToSmallCount(KEEP_HANDLES); #endif auto clazzGCPtr = obj->getClassGCPtr(); #ifndef NDEBUG if (clazzGCPtr.get(runtime)->isDictionary()) ++NumGetByIdDict; #else (void)NumGetByIdDict; #endif \/\/ If we have a cache hit, reuse the cached offset and immediately \/\/ return the property. if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) { ++NumGetByIdCacheHits; CAPTURE_IP_ASSIGN( O1REG(GetById), JSObject::getNamedSlotValue( obj, runtime, cacheEntry->slot)); ip = nextIP; DISPATCH; } auto id = ID(idVal); NamedPropertyDescriptor desc; CAPTURE_IP_ASSIGN( OptValue fastPathResult, JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc)); if (LLVM_LIKELY( fastPathResult.hasValue() && fastPathResult.getValue()) && !desc.flags.accessor) { ++NumGetByIdFastPaths; \/\/ cacheIdx == 0 indicates no caching so don't update the cache in \/\/ those cases. auto *clazz = clazzGCPtr.getNonNull(runtime); if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) && LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) { #ifdef HERMES_SLOW_DEBUG if (cacheEntry->clazz && cacheEntry->clazz != clazzGCPtr.getStorageType()) ++NumGetByIdCacheEvicts; #else (void)NumGetByIdCacheEvicts; #endif \/\/ Cache the class, id and property slot. cacheEntry->clazz = clazzGCPtr.getStorageType(); cacheEntry->slot = desc.slot; } CAPTURE_IP_ASSIGN( O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc)); ip = nextIP; DISPATCH; } \/\/ The cache may also be populated via the prototype of the object. \/\/ This value is only reliable if the fast path was a definite \/\/ not-found. if (fastPathResult.hasValue() && !fastPathResult.getValue() && !obj->isProxyObject()) { CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime)); \/\/ TODO: This isLazy check is because a lazy object is reported as \/\/ having no properties and therefore cannot contain the property. \/\/ This check does not belong here, it should be merged into \/\/ tryGetOwnNamedDescriptorFast(). if (parent && cacheEntry->clazz == parent->getClassGCPtr().getStorageType() && LLVM_LIKELY(!obj->isLazy())) { ++NumGetByIdProtoHits; CAPTURE_IP_ASSIGN( O1REG(GetById), JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot)); ip = nextIP; DISPATCH; } } #ifdef HERMES_SLOW_DEBUG CAPTURE_IP_ASSIGN( JSObject * propObj, JSObject::getNamedDescriptor( Handle::vmcast(&O2REG(GetById)), runtime, id, desc)); if (propObj) { if (desc.flags.accessor) ++NumGetByIdAccessor; else if (propObj != vmcast(O2REG(GetById))) ++NumGetByIdProto; } else { ++NumGetByIdNotFound; } #else (void)NumGetByIdAccessor; (void)NumGetByIdProto; (void)NumGetByIdNotFound; #endif #ifdef HERMES_SLOW_DEBUG auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry->clazz.get(runtime, &runtime->getHeap()) : nullptr; #endif ++NumGetByIdSlow; CAPTURE_IP_ASSIGN( resPH, JSObject::getNamed_RJS( Handle::vmcast(&O2REG(GetById)), runtime, id, !tryProp ? defaultPropOpFlags : defaultPropOpFlags.plusMustExist(), cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry : nullptr)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } #ifdef HERMES_SLOW_DEBUG if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass && cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) { ++NumGetByIdCacheEvicts; } #endif } else { ++NumGetByIdTransient; assert(!tryProp && \"TryGetById can only be used on the global object\"); \/* Slow path. *\/ CAPTURE_IP_ASSIGN( resPH, Interpreter::getByIdTransient_RJS( runtime, Handle<>(&O2REG(GetById)), ID(idVal))); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } } O1REG(GetById) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(TryPutByIdLong) { tryProp = true; idVal = ip->iTryPutByIdLong.op4; nextIP = NEXTINST(TryPutByIdLong); goto putById; } CASE(PutByIdLong) { tryProp = false; idVal = ip->iPutByIdLong.op4; nextIP = NEXTINST(PutByIdLong); goto putById; } CASE(TryPutById) { tryProp = true; idVal = ip->iTryPutById.op4; nextIP = NEXTINST(TryPutById); goto putById; } CASE(PutById) { tryProp = false; idVal = ip->iPutById.op4; nextIP = NEXTINST(PutById); } putById : { ++NumPutById; if (LLVM_LIKELY(O1REG(PutById).isObject())) { auto *obj = vmcast(O1REG(PutById)); auto cacheIdx = ip->iPutById.op3; auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx); #ifdef HERMESVM_PROFILER_BB { HERMES_SLOW_ASSERT( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"unaccounted handles were created\"); auto objHandle = runtime->makeHandle(obj); auto cacheHCPtr = vmcast_or_null(static_cast( cacheEntry->clazz.get(runtime, &runtime->getHeap()))); CAPTURE_IP(runtime->recordHiddenClass( curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr)); \/\/ obj may be moved by GC due to recordHiddenClass obj = objHandle.get(); } gcScope.flushToSmallCount(KEEP_HANDLES); #endif auto clazzGCPtr = obj->getClassGCPtr(); \/\/ If we have a cache hit, reuse the cached offset and immediately \/\/ return the property. if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) { ++NumPutByIdCacheHits; CAPTURE_IP(JSObject::setNamedSlotValue( obj, runtime, cacheEntry->slot, O2REG(PutById))); ip = nextIP; DISPATCH; } auto id = ID(idVal); NamedPropertyDescriptor desc; CAPTURE_IP_ASSIGN( OptValue hasOwnProp, JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc)); if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) && !desc.flags.accessor && desc.flags.writable && !desc.flags.internalSetter) { ++NumPutByIdFastPaths; \/\/ cacheIdx == 0 indicates no caching so don't update the cache in \/\/ those cases. auto *clazz = clazzGCPtr.getNonNull(runtime); if (LLVM_LIKELY(!clazz->isDictionary()) && LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) { #ifdef HERMES_SLOW_DEBUG if (cacheEntry->clazz && cacheEntry->clazz != clazzGCPtr.getStorageType()) ++NumPutByIdCacheEvicts; #else (void)NumPutByIdCacheEvicts; #endif \/\/ Cache the class and property slot. cacheEntry->clazz = clazzGCPtr.getStorageType(); cacheEntry->slot = desc.slot; } CAPTURE_IP(JSObject::setNamedSlotValue( obj, runtime, desc.slot, O2REG(PutById))); ip = nextIP; DISPATCH; } CAPTURE_IP_ASSIGN( auto putRes, JSObject::putNamed_RJS( Handle::vmcast(&O1REG(PutById)), runtime, id, Handle<>(&O2REG(PutById)), !tryProp ? defaultPropOpFlags : defaultPropOpFlags.plusMustExist())); if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) { goto exception; } } else { ++NumPutByIdTransient; assert(!tryProp && \"TryPutById can only be used on the global object\"); CAPTURE_IP_ASSIGN( auto retStatus, Interpreter::putByIdTransient_RJS( runtime, Handle<>(&O1REG(PutById)), ID(idVal), Handle<>(&O2REG(PutById)), strictMode)); if (retStatus == ExecutionStatus::EXCEPTION) { goto exception; } } gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(GetByVal) { CallResult propRes{ExecutionStatus::EXCEPTION}; if (LLVM_LIKELY(O2REG(GetByVal).isObject())) { CAPTURE_IP_ASSIGN( resPH, JSObject::getComputed_RJS( Handle::vmcast(&O2REG(GetByVal)), runtime, Handle<>(&O3REG(GetByVal)))); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } } else { \/\/ This is the \"slow path\". CAPTURE_IP_ASSIGN( resPH, Interpreter::getByValTransient_RJS( runtime, Handle<>(&O2REG(GetByVal)), Handle<>(&O3REG(GetByVal)))); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(GetByVal) = resPH->get(); ip = NEXTINST(GetByVal); DISPATCH; } CASE(PutByVal) { if (LLVM_LIKELY(O1REG(PutByVal).isObject())) { CAPTURE_IP_ASSIGN( auto putRes, JSObject::putComputed_RJS( Handle::vmcast(&O1REG(PutByVal)), runtime, Handle<>(&O2REG(PutByVal)), Handle<>(&O3REG(PutByVal)), defaultPropOpFlags)); if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) { goto exception; } } else { \/\/ This is the \"slow path\". CAPTURE_IP_ASSIGN( auto retStatus, Interpreter::putByValTransient_RJS( runtime, Handle<>(&O1REG(PutByVal)), Handle<>(&O2REG(PutByVal)), Handle<>(&O3REG(PutByVal)), strictMode)); if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) { goto exception; } } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(PutByVal); DISPATCH; } CASE(PutOwnByIndexL) { nextIP = NEXTINST(PutOwnByIndexL); idVal = ip->iPutOwnByIndexL.op3; goto putOwnByIndex; } CASE(PutOwnByIndex) { nextIP = NEXTINST(PutOwnByIndex); idVal = ip->iPutOwnByIndex.op3; } putOwnByIndex : { tmpHandle = HermesValue::encodeDoubleValue(idVal); CAPTURE_IP(JSObject::defineOwnComputedPrimitive( Handle::vmcast(&O1REG(PutOwnByIndex)), runtime, tmpHandle, DefinePropertyFlags::getDefaultNewPropertyFlags(), Handle<>(&O2REG(PutOwnByIndex)))); gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = nextIP; DISPATCH; } CASE(GetPNameList) { CAPTURE_IP_ASSIGN( auto pRes, handleGetPNameList(runtime, frameRegs, ip)); if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(GetPNameList); DISPATCH; } CASE(GetNextPName) { { assert( vmisa(O2REG(GetNextPName)) && \"GetNextPName's second op must be BigStorage\"); auto obj = Handle::vmcast(&O3REG(GetNextPName)); auto arr = Handle::vmcast(&O2REG(GetNextPName)); uint32_t idx = O4REG(GetNextPName).getNumber(); uint32_t size = O5REG(GetNextPName).getNumber(); MutableHandle propObj{runtime}; \/\/ Loop until we find a property which is present. while (idx < size) { tmpHandle = arr->at(idx); ComputedPropertyDescriptor desc; CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor( obj, runtime, tmpHandle, propObj, desc)); if (LLVM_LIKELY(propObj)) break; ++idx; } if (idx < size) { \/\/ We must return the property as a string if (tmpHandle->isNumber()) { CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle)); assert( status == ExecutionStatus::RETURNED && \"toString on number cannot fail\"); tmpHandle = status->getHermesValue(); } O1REG(GetNextPName) = tmpHandle.get(); O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1); } else { O1REG(GetNextPName) = HermesValue::encodeUndefinedValue(); } } gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = NEXTINST(GetNextPName); DISPATCH; } CASE(ToNumber) { if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) { O1REG(ToNumber) = O2REG(ToNumber); ip = NEXTINST(ToNumber); } else { CAPTURE_IP_ASSIGN( res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber)))); if (res == ExecutionStatus::EXCEPTION) goto exception; gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(ToNumber) = res.getValue(); ip = NEXTINST(ToNumber); } DISPATCH; } CASE(ToInt32) { CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) goto exception; gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(ToInt32) = res.getValue(); ip = NEXTINST(ToInt32); DISPATCH; } CASE(AddEmptyString) { if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) { O1REG(AddEmptyString) = O2REG(AddEmptyString); ip = NEXTINST(AddEmptyString); } else { CAPTURE_IP_ASSIGN( res, toPrimitive_RJS( runtime, Handle<>(&O2REG(AddEmptyString)), PreferredType::NONE)); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) goto exception; tmpHandle = res.getValue(); CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle)); if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) goto exception; tmpHandle.clear(); gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(AddEmptyString) = strRes->getHermesValue(); ip = NEXTINST(AddEmptyString); } DISPATCH; } CASE(Jmp) { ip = IPADD(ip->iJmp.op1); DISPATCH; } CASE(JmpLong) { ip = IPADD(ip->iJmpLong.op1); DISPATCH; } CASE(JmpTrue) { if (toBoolean(O2REG(JmpTrue))) ip = IPADD(ip->iJmpTrue.op1); else ip = NEXTINST(JmpTrue); DISPATCH; } CASE(JmpTrueLong) { if (toBoolean(O2REG(JmpTrueLong))) ip = IPADD(ip->iJmpTrueLong.op1); else ip = NEXTINST(JmpTrueLong); DISPATCH; } CASE(JmpFalse) { if (!toBoolean(O2REG(JmpFalse))) ip = IPADD(ip->iJmpFalse.op1); else ip = NEXTINST(JmpFalse); DISPATCH; } CASE(JmpFalseLong) { if (!toBoolean(O2REG(JmpFalseLong))) ip = IPADD(ip->iJmpFalseLong.op1); else ip = NEXTINST(JmpFalseLong); DISPATCH; } CASE(JmpUndefined) { if (O2REG(JmpUndefined).isUndefined()) ip = IPADD(ip->iJmpUndefined.op1); else ip = NEXTINST(JmpUndefined); DISPATCH; } CASE(JmpUndefinedLong) { if (O2REG(JmpUndefinedLong).isUndefined()) ip = IPADD(ip->iJmpUndefinedLong.op1); else ip = NEXTINST(JmpUndefinedLong); DISPATCH; } CASE(Add) { if (LLVM_LIKELY( O2REG(Add).isNumber() && O3REG(Add).isNumber())) { \/* Fast-path. *\/ CASE(AddN) { O1REG(Add) = HermesValue::encodeDoubleValue( O2REG(Add).getNumber() + O3REG(Add).getNumber()); ip = NEXTINST(Add); DISPATCH; } } CAPTURE_IP_ASSIGN( res, addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add)))); if (res == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(Add) = res.getValue(); ip = NEXTINST(Add); DISPATCH; } CASE(BitNot) { if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { \/* Fast-path. *\/ O1REG(BitNot) = HermesValue::encodeDoubleValue( ~hermes::truncateToInt32(O2REG(BitNot).getNumber())); ip = NEXTINST(BitNot); DISPATCH; } CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot)))); if (res == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(BitNot) = HermesValue::encodeDoubleValue( ~static_cast(res->getNumber())); ip = NEXTINST(BitNot); DISPATCH; } CASE(GetArgumentsLength) { \/\/ If the arguments object hasn't been created yet. if (O2REG(GetArgumentsLength).isUndefined()) { O1REG(GetArgumentsLength) = HermesValue::encodeNumberValue(FRAME.getArgCount()); ip = NEXTINST(GetArgumentsLength); DISPATCH; } \/\/ The arguments object has been created, so this is a regular property \/\/ get. assert( O2REG(GetArgumentsLength).isObject() && \"arguments lazy register is not an object\"); CAPTURE_IP_ASSIGN( resPH, JSObject::getNamed_RJS( Handle::vmcast(&O2REG(GetArgumentsLength)), runtime, Predefined::getSymbolID(Predefined::length))); if (resPH == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(GetArgumentsLength) = resPH->get(); ip = NEXTINST(GetArgumentsLength); DISPATCH; } CASE(GetArgumentsPropByVal) { \/\/ If the arguments object hasn't been created yet and we have a \/\/ valid integer index, we use the fast path. if (O3REG(GetArgumentsPropByVal).isUndefined()) { \/\/ If this is an integer index. if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) { \/\/ Is this an existing argument? if (*index < FRAME.getArgCount()) { O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index); ip = NEXTINST(GetArgumentsPropByVal); DISPATCH; } } } \/\/ Slow path. CAPTURE_IP_ASSIGN( auto res, getArgumentsPropByValSlowPath_RJS( runtime, &O3REG(GetArgumentsPropByVal), &O2REG(GetArgumentsPropByVal), FRAME.getCalleeClosureHandleUnsafe(), strictMode)); if (res == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(GetArgumentsPropByVal) = res->getHermesValue(); ip = NEXTINST(GetArgumentsPropByVal); DISPATCH; } CASE(ReifyArguments) { \/\/ If the arguments object was already created, do nothing. if (!O1REG(ReifyArguments).isUndefined()) { assert( O1REG(ReifyArguments).isObject() && \"arguments lazy register is not an object\"); ip = NEXTINST(ReifyArguments); DISPATCH; } CAPTURE_IP_ASSIGN( resArgs, reifyArgumentsSlowPath( runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode)); if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(ReifyArguments) = resArgs->getHermesValue(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(ReifyArguments); DISPATCH; } CASE(NewObject) { \/\/ Create a new object using the built-in constructor. Note that the \/\/ built-in constructor is empty, so we don't actually need to call \/\/ it. CAPTURE_IP_ASSIGN( O1REG(NewObject), JSObject::create(runtime).getHermesValue()); assert( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"Should not create handles.\"); ip = NEXTINST(NewObject); DISPATCH; } CASE(NewObjectWithParent) { CAPTURE_IP_ASSIGN( O1REG(NewObjectWithParent), JSObject::create( runtime, O2REG(NewObjectWithParent).isObject() ? Handle::vmcast(&O2REG(NewObjectWithParent)) : O2REG(NewObjectWithParent).isNull() ? Runtime::makeNullHandle() : Handle::vmcast(&runtime->objectPrototype)) .getHermesValue()); assert( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"Should not create handles.\"); ip = NEXTINST(NewObjectWithParent); DISPATCH; } CASE(NewObjectWithBuffer) { CAPTURE_IP_ASSIGN( resPH, Interpreter::createObjectFromBuffer( runtime, curCodeBlock, ip->iNewObjectWithBuffer.op3, ip->iNewObjectWithBuffer.op4, ip->iNewObjectWithBuffer.op5)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(NewObjectWithBuffer) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(NewObjectWithBuffer); DISPATCH; } CASE(NewObjectWithBufferLong) { CAPTURE_IP_ASSIGN( resPH, Interpreter::createObjectFromBuffer( runtime, curCodeBlock, ip->iNewObjectWithBufferLong.op3, ip->iNewObjectWithBufferLong.op4, ip->iNewObjectWithBufferLong.op5)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(NewObjectWithBufferLong) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(NewObjectWithBufferLong); DISPATCH; } CASE(NewArray) { \/\/ Create a new array using the built-in constructor. Note that the \/\/ built-in constructor is empty, so we don't actually need to call \/\/ it. CAPTURE_IP_ASSIGN( auto createRes, JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2)); if (createRes == ExecutionStatus::EXCEPTION) { goto exception; } O1REG(NewArray) = createRes->getHermesValue(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(NewArray); DISPATCH; } CASE(NewArrayWithBuffer) { CAPTURE_IP_ASSIGN( resPH, Interpreter::createArrayFromBuffer( runtime, curCodeBlock, ip->iNewArrayWithBuffer.op2, ip->iNewArrayWithBuffer.op3, ip->iNewArrayWithBuffer.op4)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(NewArrayWithBuffer) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = NEXTINST(NewArrayWithBuffer); DISPATCH; } CASE(NewArrayWithBufferLong) { CAPTURE_IP_ASSIGN( resPH, Interpreter::createArrayFromBuffer( runtime, curCodeBlock, ip->iNewArrayWithBufferLong.op2, ip->iNewArrayWithBufferLong.op3, ip->iNewArrayWithBufferLong.op4)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(NewArrayWithBufferLong) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = NEXTINST(NewArrayWithBufferLong); DISPATCH; } CASE(CreateThis) { \/\/ Registers: output, prototype, closure. if (LLVM_UNLIKELY(!vmisa(O3REG(CreateThis)))) { CAPTURE_IP(runtime->raiseTypeError(\"constructor is not callable\")); goto exception; } CAPTURE_IP_ASSIGN( auto res, Callable::newObject( Handle::vmcast(&O3REG(CreateThis)), runtime, Handle::vmcast( O2REG(CreateThis).isObject() ? &O2REG(CreateThis) : &runtime->objectPrototype))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(CreateThis) = res->getHermesValue(); ip = NEXTINST(CreateThis); DISPATCH; } CASE(SelectObject) { \/\/ Registers: output, thisObject, constructorReturnValue. O1REG(SelectObject) = O3REG(SelectObject).isObject() ? O3REG(SelectObject) : O2REG(SelectObject); ip = NEXTINST(SelectObject); DISPATCH; } CASE(Eq) CASE(Neq) { CAPTURE_IP_ASSIGN( res, abstractEqualityTest_RJS( runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq)))); if (res == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(Eq) = ip->opCode == OpCode::Eq ? res.getValue() : HermesValue::encodeBoolValue(!res->getBool()); ip = NEXTINST(Eq); DISPATCH; } CASE(StrictEq) { O1REG(StrictEq) = HermesValue::encodeBoolValue( strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq))); ip = NEXTINST(StrictEq); DISPATCH; } CASE(StrictNeq) { O1REG(StrictNeq) = HermesValue::encodeBoolValue( !strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq))); ip = NEXTINST(StrictNeq); DISPATCH; } CASE(Not) { O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not))); ip = NEXTINST(Not); DISPATCH; } CASE(Negate) { if (LLVM_LIKELY(O2REG(Negate).isNumber())) { O1REG(Negate) = HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber()); } else { CAPTURE_IP_ASSIGN( res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate)))); if (res == ExecutionStatus::EXCEPTION) goto exception; gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber()); } ip = NEXTINST(Negate); DISPATCH; } CASE(TypeOf) { CAPTURE_IP_ASSIGN( O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf)))); ip = NEXTINST(TypeOf); DISPATCH; } CASE(Mod) { \/\/ We use fmod here for simplicity. Theoretically fmod behaves slightly \/\/ differently than the ECMAScript Spec. fmod applies round-towards-zero \/\/ for the remainder when it's not representable by a double; while the \/\/ spec requires round-to-nearest. As an example, 5 % 0.7 will give \/\/ 0.10000000000000031 using fmod, but using the rounding style \/\/ described \/\/ by the spec, the output should really be 0.10000000000000053. \/\/ Such difference can be ignored in practice. if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) { \/* Fast-path. *\/ O1REG(Mod) = HermesValue::encodeDoubleValue( std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber())); ip = NEXTINST(Mod); DISPATCH; } CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod)))); if (res == ExecutionStatus::EXCEPTION) goto exception; double left = res->getDouble(); CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod)))); if (res == ExecutionStatus::EXCEPTION) goto exception; O1REG(Mod) = HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble())); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(Mod); DISPATCH; } CASE(InstanceOf) { CAPTURE_IP_ASSIGN( auto result, instanceOfOperator_RJS( runtime, Handle<>(&O2REG(InstanceOf)), Handle<>(&O3REG(InstanceOf)))); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(InstanceOf); DISPATCH; } CASE(IsIn) { { if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) { CAPTURE_IP(runtime->raiseTypeError( \"right operand of 'in' is not an object\")); goto exception; } CAPTURE_IP_ASSIGN( auto cr, JSObject::hasComputed( Handle::vmcast(&O3REG(IsIn)), runtime, Handle<>(&O2REG(IsIn)))); if (cr == ExecutionStatus::EXCEPTION) { goto exception; } O1REG(IsIn) = HermesValue::encodeBoolValue(*cr); } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(IsIn); DISPATCH; } CASE(PutNewOwnByIdShort) { nextIP = NEXTINST(PutNewOwnByIdShort); idVal = ip->iPutNewOwnByIdShort.op3; goto putOwnById; } CASE(PutNewOwnNEByIdLong) CASE(PutNewOwnByIdLong) { nextIP = NEXTINST(PutNewOwnByIdLong); idVal = ip->iPutNewOwnByIdLong.op3; goto putOwnById; } CASE(PutNewOwnNEById) CASE(PutNewOwnById) { nextIP = NEXTINST(PutNewOwnById); idVal = ip->iPutNewOwnById.op3; } putOwnById : { assert( O1REG(PutNewOwnById).isObject() && \"Object argument of PutNewOwnById must be an object\"); CAPTURE_IP_ASSIGN( auto res, JSObject::defineNewOwnProperty( Handle::vmcast(&O1REG(PutNewOwnById)), runtime, ID(idVal), ip->opCode <= OpCode::PutNewOwnByIdLong ? PropertyFlags::defaultNewNamedPropertyFlags() : PropertyFlags::nonEnumerablePropertyFlags(), Handle<>(&O2REG(PutNewOwnById)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(DelByIdLong) { idVal = ip->iDelByIdLong.op3; nextIP = NEXTINST(DelByIdLong); goto DelById; } CASE(DelById) { idVal = ip->iDelById.op3; nextIP = NEXTINST(DelById); } DelById : { if (LLVM_LIKELY(O2REG(DelById).isObject())) { CAPTURE_IP_ASSIGN( auto status, JSObject::deleteNamed( Handle::vmcast(&O2REG(DelById)), runtime, ID(idVal), defaultPropOpFlags)); if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue()); } else { \/\/ This is the \"slow path\". CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \/\/ If an exception is thrown, likely we are trying to convert \/\/ undefined\/null to an object. Passing over the name of the property \/\/ so that we could emit more meaningful error messages. CAPTURE_IP(amendPropAccessErrorMsgWithPropName( runtime, Handle<>(&O2REG(DelById)), \"delete\", ID(idVal))); goto exception; } tmpHandle = res.getValue(); CAPTURE_IP_ASSIGN( auto status, JSObject::deleteNamed( Handle::vmcast(tmpHandle), runtime, ID(idVal), defaultPropOpFlags)); if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue()); tmpHandle.clear(); } gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(DelByVal) { if (LLVM_LIKELY(O2REG(DelByVal).isObject())) { CAPTURE_IP_ASSIGN( auto status, JSObject::deleteComputed( Handle::vmcast(&O2REG(DelByVal)), runtime, Handle<>(&O3REG(DelByVal)), defaultPropOpFlags)); if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue()); } else { \/\/ This is the \"slow path\". CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } tmpHandle = res.getValue(); CAPTURE_IP_ASSIGN( auto status, JSObject::deleteComputed( Handle::vmcast(tmpHandle), runtime, Handle<>(&O3REG(DelByVal)), defaultPropOpFlags)); if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue()); } gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = NEXTINST(DelByVal); DISPATCH; } CASE(CreateRegExp) { { \/\/ Create the RegExp object. CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime)); \/\/ Initialize the regexp. CAPTURE_IP_ASSIGN( auto pattern, runtime->makeHandle(curCodeBlock->getRuntimeModule() ->getStringPrimFromStringIDMayAllocate( ip->iCreateRegExp.op2))); CAPTURE_IP_ASSIGN( auto flags, runtime->makeHandle(curCodeBlock->getRuntimeModule() ->getStringPrimFromStringIDMayAllocate( ip->iCreateRegExp.op3))); CAPTURE_IP_ASSIGN( auto bytecode, curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID( ip->iCreateRegExp.op4)); CAPTURE_IP_ASSIGN( auto initRes, JSRegExp::initialize(re, runtime, pattern, flags, bytecode)); if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) { goto exception; } \/\/ Done, return the new object. O1REG(CreateRegExp) = re.getHermesValue(); } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateRegExp); DISPATCH; } CASE(SwitchImm) { if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) { double numVal = O1REG(SwitchImm).getNumber(); uint32_t uintVal = (uint32_t)numVal; if (LLVM_LIKELY(numVal == uintVal) && \/\/ Only integers. LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && \/\/ Bounds checking. LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) \/\/ Bounds checking. { \/\/ Calculate the offset into the bytecode where the jump table for \/\/ this SwitchImm starts. const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr( (const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t)); \/\/ Read the offset from the table. \/\/ Must be signed to account for backwards branching. const int32_t *loc = (const int32_t *)tablestart + uintVal - ip->iSwitchImm.op4; ip = IPADD(*loc); DISPATCH; } } \/\/ Wrong type or out of range, jump to default. ip = IPADD(ip->iSwitchImm.op3); DISPATCH; } LOAD_CONST( LoadConstUInt8, HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2)); LOAD_CONST( LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2)); LOAD_CONST( LoadConstDouble, HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2)); LOAD_CONST_CAPTURE_IP( LoadConstString, HermesValue::encodeStringValue( curCodeBlock->getRuntimeModule() ->getStringPrimFromStringIDMayAllocate( ip->iLoadConstString.op2))); LOAD_CONST_CAPTURE_IP( LoadConstStringLongIndex, HermesValue::encodeStringValue( curCodeBlock->getRuntimeModule() ->getStringPrimFromStringIDMayAllocate( ip->iLoadConstStringLongIndex.op2))); LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue()); LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue()); LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true)); LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false)); LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0)); BINOP(Sub, doSub); BINOP(Mul, doMult); BINOP(Div, doDiv); BITWISEBINOP(BitAnd, &); BITWISEBINOP(BitOr, |); BITWISEBINOP(BitXor, ^); \/\/ For LShift, we need to use toUInt32 first because lshift on negative \/\/ numbers is undefined behavior in theory. SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t); SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t); SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t); CONDOP(Less, <, lessOp_RJS); CONDOP(LessEq, <=, lessEqualOp_RJS); CONDOP(Greater, >, greaterOp_RJS); CONDOP(GreaterEq, >=, greaterEqualOp_RJS); JCOND(Less, <, lessOp_RJS); JCOND(LessEqual, <=, lessEqualOp_RJS); JCOND(Greater, >, greaterOp_RJS); JCOND(GreaterEqual, >=, greaterEqualOp_RJS); JCOND_STRICT_EQ_IMPL( JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual)); JCOND_STRICT_EQ_IMPL( JStrictEqual, Long, IPADD(ip->iJStrictEqualLong.op1), NEXTINST(JStrictEqualLong)); JCOND_STRICT_EQ_IMPL( JStrictNotEqual, , NEXTINST(JStrictNotEqual), IPADD(ip->iJStrictNotEqual.op1)); JCOND_STRICT_EQ_IMPL( JStrictNotEqual, Long, NEXTINST(JStrictNotEqualLong), IPADD(ip->iJStrictNotEqualLong.op1)); JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual)); JCOND_EQ_IMPL( JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong)); JCOND_EQ_IMPL( JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1)); JCOND_EQ_IMPL( JNotEqual, Long, NEXTINST(JNotEqualLong), IPADD(ip->iJNotEqualLong.op1)); CASE_OUTOFLINE(PutOwnByVal); CASE_OUTOFLINE(PutOwnGetterSetterByVal); CASE_OUTOFLINE(DirectEval); CASE_OUTOFLINE(IteratorBegin); CASE_OUTOFLINE(IteratorNext); CASE(IteratorClose) { if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) { \/\/ The iterator must be closed if it's still an object. \/\/ That means it was never an index and is not done iterating (a state \/\/ which is indicated by `undefined`). CAPTURE_IP_ASSIGN( auto res, iteratorClose( runtime, Handle::vmcast(&O1REG(IteratorClose)), Runtime::getEmptyValue())); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { if (ip->iIteratorClose.op2 && !isUncatchableError(runtime->thrownValue_)) { \/\/ Ignore inner exception. runtime->clearThrownValue(); } else { goto exception; } } gcScope.flushToSmallCount(KEEP_HANDLES); } ip = NEXTINST(IteratorClose); DISPATCH; } CASE(_last) { llvm_unreachable(\"Invalid opcode _last\"); } } llvm_unreachable(\"unreachable\"); \/\/ We arrive here if we couldn't allocate the registers for the current frame. stackOverflow: CAPTURE_IP(runtime->raiseStackOverflow( Runtime::StackOverflowKind::JSRegisterStack)); \/\/ We arrive here when we raised an exception in a callee, but we don't want \/\/ the callee to be able to handle it. handleExceptionInParent: \/\/ Restore the caller code block and IP. curCodeBlock = FRAME.getSavedCodeBlock(); ip = FRAME.getSavedIP(); \/\/ Pop to the previous frame where technically the error happened. frameRegs = &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef(); \/\/ If we are coming from native code, return. if (!curCodeBlock) return ExecutionStatus::EXCEPTION; \/\/ Return because of recursive calling structure #ifdef HERMESVM_PROFILER_EXTERN return ExecutionStatus::EXCEPTION; #endif \/\/ Handle the exception. exception: UPDATE_OPCODE_TIME_SPENT; assert( !runtime->thrownValue_.isEmpty() && \"thrownValue unavailable at exception\"); bool catchable = true; \/\/ If this is an Error object that was thrown internally, it didn't have \/\/ access to the current codeblock and IP, so collect the stack trace here. if (auto *jsError = dyn_vmcast(runtime->thrownValue_)) { catchable = jsError->catchable(); if (!jsError->getStackTrace()) { \/\/ Temporarily clear the thrown value for following operations. CAPTURE_IP_ASSIGN( auto errorHandle, runtime->makeHandle(vmcast(runtime->thrownValue_))); runtime->clearThrownValue(); CAPTURE_IP(JSError::recordStackTrace( errorHandle, runtime, false, curCodeBlock, ip)); \/\/ Restore the thrown value. runtime->setThrownValue(errorHandle.getHermesValue()); } } gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); #ifdef HERMES_ENABLE_DEBUGGER if (SingleStep) { \/\/ If we're single stepping, don't bother with any more checks, \/\/ and simply signal that we should continue execution with an exception. state.codeBlock = curCodeBlock; state.offset = CUROFFSET; return ExecutionStatus::EXCEPTION; } using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode; auto mode = runtime->debugger_.getPauseOnThrowMode(); if (mode != PauseOnThrowMode::None) { if (!runtime->debugger_.isDebugging()) { \/\/ Determine whether the PauseOnThrowMode requires us to stop here. bool caught = runtime->debugger_ .findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET)) .hasValue(); bool shouldStop = mode == PauseOnThrowMode::All || (mode == PauseOnThrowMode::Uncaught && !caught); if (shouldStop) { \/\/ When runDebugger is invoked after an exception, \/\/ stepping should never happen internally. \/\/ Any step is a step to an exception handler, which we do \/\/ directly here in the interpreter. \/\/ Thus, the result state should be the same as the input state. InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET}; CAPTURE_IP_ASSIGN( ExecutionStatus resultStatus, runtime->debugger_.runDebugger( Debugger::RunReason::Exception, tmpState)); (void)resultStatus; assert( tmpState == InterpreterState(curCodeBlock, CUROFFSET) && \"not allowed to step internally in a pauseOnThrow\"); gcScope.flushToSmallCount(KEEP_HANDLES); } } } #endif int32_t handlerOffset = 0; \/\/ If the exception is not catchable, skip found catch blocks. while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) == -1) || !catchable) { PROFILER_EXIT_FUNCTION(curCodeBlock); #ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES runtime->popCallStack(); #endif \/\/ Restore the code block and IP. curCodeBlock = FRAME.getSavedCodeBlock(); ip = FRAME.getSavedIP(); \/\/ Pop a stack frame. frameRegs = &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef(); SLOW_DEBUG( dbgs() << \"function exit with exception: restored stackLevel=\" << runtime->getStackLevel() << \"\\n\"); \/\/ Are we returning to native code? if (!curCodeBlock) { SLOW_DEBUG( dbgs() << \"function exit with exception: returning to native code\\n\"); return ExecutionStatus::EXCEPTION; } assert( isCallType(ip->opCode) && \"return address is not Call-type instruction\"); \/\/ Return because of recursive calling structure #ifdef HERMESVM_PROFILER_EXTERN return ExecutionStatus::EXCEPTION; #endif } INIT_STATE_FOR_CODEBLOCK(curCodeBlock); ip = IPADD(handlerOffset - CUROFFSET); } }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":71895,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MaxTextExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False when converting or mogrifying *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; \/* Skip nominal layer count, frame count, and play time *\/ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\", \"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, \"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); mng_info=MngInfoFreeStruct(mng_info); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (((p-chunk) < (long) length) && *p) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { if (loop_iters > GetMagickResourceLimit(ListLengthResource)) loop_iters=GetMagickResourceLimit(ListLengthResource); if (loop_iters >= 2147483647L) loop_iters=2147483647L; mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters \", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(png_uint_32) p[12] << 8) & png_uint_32) p[13]; else basi_red=0; if (length > 15) basi_green=(png_uint_32) p[14] << 8) & png_uint_32) p[15]; else basi_green=0; if (length > 17) basi_blue=(png_uint_32) p[16] << 8) & png_uint_32) p[17]; else basi_blue=0; if (length > 19) basi_alpha=(png_uint_32) p[18] << 8) & png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { if (prev != (PixelPacket *) NULL) prev=(PixelPacket *) RelinquishMagickMemory(prev); if (next != (PixelPacket *) NULL) next=(PixelPacket *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (PixelPacket *) NULL) break; q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { \/* Interpolate *\/ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))\/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ else { \/* Interpolate *\/ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":174797,"input":"void CWebServer::GetJSonDevices( Json::Value &root, const std::string &rused, const std::string &rfilter, const std::string &order, const std::string &rowid, const std::string &planID, const std::string &floorID, const bool bDisplayHidden, const bool bDisplayDisabled, const bool bFetchFavorites, const time_t LastUpdate, const std::string &username, const std::string &hardwareid) { std::vector > result; time_t now = mytime(NULL); struct tm tm1; localtime_r(&now, &tm1); struct tm tLastUpdate; localtime_r(&now, &tLastUpdate); const time_t iLastUpdate = LastUpdate - 1; int SensorTimeOut = 60; m_sql.GetPreferencesVar(\"SensorTimeout\", SensorTimeOut); std::map _hardwareNames; result = m_sql.safe_query(\"SELECT ID, Name, Enabled, Type, Mode1, Mode2 FROM Hardware\"); if (!result.empty()) { int ii = 0; for (const auto & itt : result) { std::vector sd = itt; _tHardwareListInt tlist; int ID = atoi(sd[0].c_str()); tlist.Name = sd[1]; tlist.Enabled = (atoi(sd[2].c_str()) != 0); tlist.HardwareTypeVal = atoi(sd[3].c_str()); #ifndef ENABLE_PYTHON tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal); #else if (tlist.HardwareTypeVal != HTYPE_PythonPlugin) { tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal); } else { tlist.HardwareType = PluginHardwareDesc(ID); } #endif tlist.Mode1 = sd[4]; tlist.Mode2 = sd[5]; _hardwareNames[ID] = tlist; } } root[\"ActTime\"] = static_cast(now); char szTmp[300]; if (!m_mainworker.m_LastSunriseSet.empty()) { std::vector strarray; StringSplit(m_mainworker.m_LastSunriseSet, \";\", strarray); if (strarray.size() == 10) { strftime(szTmp, 80, \"%Y-%m-%d %X\", &tm1); root[\"ServerTime\"] = szTmp; root[\"Sunrise\"] = strarray[0]; root[\"Sunset\"] = strarray[1]; root[\"SunAtSouth\"] = strarray[2]; root[\"CivTwilightStart\"] = strarray[3]; root[\"CivTwilightEnd\"] = strarray[4]; root[\"NautTwilightStart\"] = strarray[5]; root[\"NautTwilightEnd\"] = strarray[6]; root[\"AstrTwilightStart\"] = strarray[7]; root[\"AstrTwilightEnd\"] = strarray[8]; root[\"DayLength\"] = strarray[9]; } } char szOrderBy[50]; std::string szQuery; bool isAlpha = true; const std::string orderBy = order.c_str(); for (size_t i = 0; i < orderBy.size(); i++) { if (!isalpha(orderBy[i])) { isAlpha = false; } } if (order.empty() || (!isAlpha)) { strcpy(szOrderBy, \"A.[Order],A.LastUpdate DESC\"); } else { sprintf(szOrderBy, \"A.[Order],A.%%s ASC\"); } unsigned char tempsign = m_sql.m_tempsign[0]; bool bHaveUser = false; int iUser = -1; unsigned int totUserDevices = 0; bool bShowScenes = true; bHaveUser = (username != \"\"); if (bHaveUser) { iUser = FindUser(username.c_str()); if (iUser != -1) { _eUserRights urights = m_users[iUser].userrights; if (urights != URIGHTS_ADMIN) { result = m_sql.safe_query(\"SELECT DeviceRowID FROM SharedDevices WHERE (SharedUserID == %lu)\", m_users[iUser].ID); totUserDevices = (unsigned int)result.size(); bShowScenes = (m_users[iUser].ActiveTabs&(1 << 1)) != 0; } } } std::set _HiddenDevices; bool bAllowDeviceToBeHidden = false; int ii = 0; if (rfilter == \"all\") { if ( (bShowScenes) && ((rused == \"all\") || (rused == \"true\")) ) { if (rowid != \"\") result = m_sql.safe_query( \"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,\" \" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description\" \" FROM Scenes as A\" \" LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)\" \" WHERE (A.ID=='%q')\", rowid.c_str()); else if ((planID != \"\") && (planID != \"0\")) result = m_sql.safe_query( \"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,\" \" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description\" \" FROM Scenes as A, DeviceToPlansMap as B WHERE (B.PlanID=='%q')\" \" AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==1) ORDER BY B.[Order]\", planID.c_str()); else if ((floorID != \"\") && (floorID != \"0\")) result = m_sql.safe_query( \"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,\" \" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description\" \" FROM Scenes as A, DeviceToPlansMap as B, Plans as C\" \" WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID) AND (B.DeviceRowID==a.ID)\" \" AND (B.DevSceneType==1) ORDER BY B.[Order]\", floorID.c_str()); else { szQuery = ( \"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,\" \" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description\" \" FROM Scenes as A\" \" LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)\" \" ORDER BY \"); szQuery += szOrderBy; result = m_sql.safe_query(szQuery.c_str(), order.c_str()); } if (!result.empty()) { for (const auto & itt : result) { std::vector sd = itt; unsigned char favorite = atoi(sd[4].c_str()); if ((bFetchFavorites) && (!favorite)) continue; std::string sLastUpdate = sd[3]; if (iLastUpdate != 0) { time_t cLastUpdate; ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst); if (cLastUpdate <= iLastUpdate) continue; } int nValue = atoi(sd[2].c_str()); unsigned char scenetype = atoi(sd[5].c_str()); int iProtected = atoi(sd[6].c_str()); std::string sSceneName = sd[1]; if (!bDisplayHidden && sSceneName[0] == '$') { continue; } if (scenetype == 0) { root[\"result\"][ii][\"Type\"] = \"Scene\"; root[\"result\"][ii][\"TypeImg\"] = \"scene\"; } else { root[\"result\"][ii][\"Type\"] = \"Group\"; root[\"result\"][ii][\"TypeImg\"] = \"group\"; } std::string thisIdx = sd[0]; if ((ii > 0) && thisIdx == root[\"result\"][ii - 1][\"idx\"].asString()) { std::string typeOfThisOne = root[\"result\"][ii][\"Type\"].asString(); if (typeOfThisOne == root[\"result\"][ii - 1][\"Type\"].asString()) { root[\"result\"][ii - 1][\"PlanIDs\"].append(atoi(sd[9].c_str())); continue; } } root[\"result\"][ii][\"idx\"] = sd[0]; root[\"result\"][ii][\"Name\"] = sSceneName; root[\"result\"][ii][\"Description\"] = sd[10]; root[\"result\"][ii][\"Favorite\"] = favorite; root[\"result\"][ii][\"Protected\"] = (iProtected != 0); root[\"result\"][ii][\"LastUpdate\"] = sLastUpdate; root[\"result\"][ii][\"PlanID\"] = sd[9].c_str(); Json::Value jsonArray; jsonArray.append(atoi(sd[9].c_str())); root[\"result\"][ii][\"PlanIDs\"] = jsonArray; if (nValue == 0) root[\"result\"][ii][\"Status\"] = \"Off\"; else if (nValue == 1) root[\"result\"][ii][\"Status\"] = \"On\"; else root[\"result\"][ii][\"Status\"] = \"Mixed\"; root[\"result\"][ii][\"Data\"] = root[\"result\"][ii][\"Status\"]; uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(1, sd[0]); root[\"result\"][ii][\"UsedByCamera\"] = (camIDX != 0) ? true : false; if (camIDX != 0) { std::stringstream scidx; scidx << camIDX; root[\"result\"][ii][\"CameraIdx\"] = scidx.str(); } root[\"result\"][ii][\"XOffset\"] = atoi(sd[7].c_str()); root[\"result\"][ii][\"YOffset\"] = atoi(sd[8].c_str()); ii++; } } } } char szData[250]; if (totUserDevices == 0) { if (rowid != \"\") { result = m_sql.safe_query( \"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used, A.Type, A.SubType,\" \" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,\" \" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,\" \" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,\" \" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,\" \" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,\" \" A.Options, A.Color \" \"FROM DeviceStatus A LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) \" \"WHERE (A.ID=='%q')\", rowid.c_str()); } else if ((planID != \"\") && (planID != \"0\")) result = m_sql.safe_query( \"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,\" \" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,\" \" A.nValue, A.sValue, A.LastUpdate, A.Favorite,\" \" A.SwitchType, A.HardwareID, A.AddjValue,\" \" A.AddjMulti, A.AddjValue2, A.AddjMulti2,\" \" A.LastLevel, A.CustomImage, A.StrParam1,\" \" A.StrParam2, A.Protected, B.XOffset, B.YOffset,\" \" B.PlanID, A.Description,\" \" A.Options, A.Color \" \"FROM DeviceStatus as A, DeviceToPlansMap as B \" \"WHERE (B.PlanID=='%q') AND (B.DeviceRowID==a.ID)\" \" AND (B.DevSceneType==0) ORDER BY B.[Order]\", planID.c_str()); else if ((floorID != \"\") && (floorID != \"0\")) result = m_sql.safe_query( \"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,\" \" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,\" \" A.nValue, A.sValue, A.LastUpdate, A.Favorite,\" \" A.SwitchType, A.HardwareID, A.AddjValue,\" \" A.AddjMulti, A.AddjValue2, A.AddjMulti2,\" \" A.LastLevel, A.CustomImage, A.StrParam1,\" \" A.StrParam2, A.Protected, B.XOffset, B.YOffset,\" \" B.PlanID, A.Description,\" \" A.Options, A.Color \" \"FROM DeviceStatus as A, DeviceToPlansMap as B,\" \" Plans as C \" \"WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID)\" \" AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) \" \"ORDER BY B.[Order]\", floorID.c_str()); else { if (!bDisplayHidden) { result = m_sql.safe_query(\"SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')\"); if (!result.empty()) { std::string pID = result[0][0]; result = m_sql.safe_query(\"SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)\", pID.c_str()); if (!result.empty()) { std::vector >::const_iterator ittP; for (ittP = result.begin(); ittP != result.end(); ++ittP) { _HiddenDevices.insert(ittP[0][0]); } } } bAllowDeviceToBeHidden = true; } if (order.empty() || (!isAlpha)) strcpy(szOrderBy, \"A.[Order],A.LastUpdate DESC\"); else { sprintf(szOrderBy, \"A.[Order],A.%%s ASC\"); } if (hardwareid != \"\") { szQuery = ( \"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType,\" \" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,\" \" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,\" \" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,\" \" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,\" \" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,\" \" A.Options, A.Color \" \"FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B \" \"ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) \" \"WHERE (A.HardwareID == %q) \" \"ORDER BY \"); szQuery += szOrderBy; result = m_sql.safe_query(szQuery.c_str(), hardwareid.c_str(), order.c_str()); } else { szQuery = ( \"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType,\" \" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,\" \" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,\" \" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,\" \" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,\" \" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,\" \" A.Options, A.Color \" \"FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B \" \"ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) \" \"ORDER BY \"); szQuery += szOrderBy; result = m_sql.safe_query(szQuery.c_str(), order.c_str()); } } } else { if (iUser == -1) { return; } if (rowid != \"\") { result = m_sql.safe_query( \"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,\" \" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,\" \" A.nValue, A.sValue, A.LastUpdate, A.Favorite,\" \" A.SwitchType, A.HardwareID, A.AddjValue,\" \" A.AddjMulti, A.AddjValue2, A.AddjMulti2,\" \" A.LastLevel, A.CustomImage, A.StrParam1,\" \" A.StrParam2, A.Protected, 0 as XOffset,\" \" 0 as YOffset, 0 as PlanID, A.Description,\" \" A.Options, A.Color \" \"FROM DeviceStatus as A, SharedDevices as B \" \"WHERE (B.DeviceRowID==a.ID)\" \" AND (B.SharedUserID==%lu) AND (A.ID=='%q')\", m_users[iUser].ID, rowid.c_str()); } else if ((planID != \"\") && (planID != \"0\")) result = m_sql.safe_query( \"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,\" \" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,\" \" A.nValue, A.sValue, A.LastUpdate, A.Favorite,\" \" A.SwitchType, A.HardwareID, A.AddjValue,\" \" A.AddjMulti, A.AddjValue2, A.AddjMulti2,\" \" A.LastLevel, A.CustomImage, A.StrParam1,\" \" A.StrParam2, A.Protected, C.XOffset,\" \" C.YOffset, C.PlanID, A.Description,\" \" A.Options, A.Color \" \"FROM DeviceStatus as A, SharedDevices as B,\" \" DeviceToPlansMap as C \" \"WHERE (C.PlanID=='%q') AND (C.DeviceRowID==a.ID)\" \" AND (B.DeviceRowID==a.ID) \" \"AND (B.SharedUserID==%lu) ORDER BY C.[Order]\", planID.c_str(), m_users[iUser].ID); else if ((floorID != \"\") && (floorID != \"0\")) result = m_sql.safe_query( \"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,\" \" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,\" \" A.nValue, A.sValue, A.LastUpdate, A.Favorite,\" \" A.SwitchType, A.HardwareID, A.AddjValue,\" \" A.AddjMulti, A.AddjValue2, A.AddjMulti2,\" \" A.LastLevel, A.CustomImage, A.StrParam1,\" \" A.StrParam2, A.Protected, C.XOffset, C.YOffset,\" \" C.PlanID, A.Description,\" \" A.Options, A.Color \" \"FROM DeviceStatus as A, SharedDevices as B,\" \" DeviceToPlansMap as C, Plans as D \" \"WHERE (D.FloorplanID=='%q') AND (D.ID==C.PlanID)\" \" AND (C.DeviceRowID==a.ID) AND (B.DeviceRowID==a.ID)\" \" AND (B.SharedUserID==%lu) ORDER BY C.[Order]\", floorID.c_str(), m_users[iUser].ID); else { if (!bDisplayHidden) { result = m_sql.safe_query(\"SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')\"); if (!result.empty()) { std::string pID = result[0][0]; result = m_sql.safe_query(\"SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)\", pID.c_str()); if (!result.empty()) { std::vector >::const_iterator ittP; for (ittP = result.begin(); ittP != result.end(); ++ittP) { _HiddenDevices.insert(ittP[0][0]); } } } bAllowDeviceToBeHidden = true; } if (order.empty() || (!isAlpha)) { strcpy(szOrderBy, \"A.[Order],A.LastUpdate DESC\"); } else { sprintf(szOrderBy, \"A.[Order],A.%%s ASC\"); } szQuery = ( \"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,\" \" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,\" \" A.nValue, A.sValue, A.LastUpdate, A.Favorite,\" \" A.SwitchType, A.HardwareID, A.AddjValue,\" \" A.AddjMulti, A.AddjValue2, A.AddjMulti2,\" \" A.LastLevel, A.CustomImage, A.StrParam1,\" \" A.StrParam2, A.Protected, IFNULL(C.XOffset,0),\" \" IFNULL(C.YOffset,0), IFNULL(C.PlanID,0), A.Description,\" \" A.Options, A.Color \" \"FROM DeviceStatus as A, SharedDevices as B \" \"LEFT OUTER JOIN DeviceToPlansMap as C ON (C.DeviceRowID==A.ID)\" \"WHERE (B.DeviceRowID==A.ID)\" \" AND (B.SharedUserID==%lu) ORDER BY \"); szQuery += szOrderBy; result = m_sql.safe_query(szQuery.c_str(), m_users[iUser].ID, order.c_str()); } } if (!result.empty()) { for (const auto & itt : result) { std::vector sd = itt; unsigned char favorite = atoi(sd[12].c_str()); if ((planID != \"\") && (planID != \"0\")) favorite = 1; if ((bFetchFavorites) && (!favorite)) continue; std::string sDeviceName = sd[3]; if (!bDisplayHidden) { if (_HiddenDevices.find(sd[0]) != _HiddenDevices.end()) continue; if (sDeviceName[0] == '$') { if (bAllowDeviceToBeHidden) continue; if (planID.size() > 0) sDeviceName = sDeviceName.substr(1); } } int hardwareID = atoi(sd[14].c_str()); std::map::iterator hItt = _hardwareNames.find(hardwareID); if (hItt != _hardwareNames.end()) { if ((!bDisplayDisabled) && (!(*hItt).second.Enabled)) continue; } unsigned int dType = atoi(sd[5].c_str()); unsigned int dSubType = atoi(sd[6].c_str()); unsigned int used = atoi(sd[4].c_str()); int nValue = atoi(sd[9].c_str()); std::string sValue = sd[10]; std::string sLastUpdate = sd[11]; if (sLastUpdate.size() > 19) sLastUpdate = sLastUpdate.substr(0, 19); if (iLastUpdate != 0) { time_t cLastUpdate; ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst); if (cLastUpdate <= iLastUpdate) continue; } _eSwitchType switchtype = (_eSwitchType)atoi(sd[13].c_str()); _eMeterType metertype = (_eMeterType)switchtype; double AddjValue = atof(sd[15].c_str()); double AddjMulti = atof(sd[16].c_str()); double AddjValue2 = atof(sd[17].c_str()); double AddjMulti2 = atof(sd[18].c_str()); int LastLevel = atoi(sd[19].c_str()); int CustomImage = atoi(sd[20].c_str()); std::string strParam1 = base64_encode(sd[21]); std::string strParam2 = base64_encode(sd[22]); int iProtected = atoi(sd[23].c_str()); std::string Description = sd[27]; std::string sOptions = sd[28]; std::string sColor = sd[29]; std::map options = m_sql.BuildDeviceOptions(sOptions); struct tm ntime; time_t checktime; ParseSQLdatetime(checktime, ntime, sLastUpdate, tm1.tm_isdst); bool bHaveTimeout = (now - checktime >= SensorTimeOut * 60); if (dType == pTypeTEMP_RAIN) continue; \/\/dont want you for now if ((rused == \"true\") && (!used)) continue; if ( (rused == \"false\") && (used) ) continue; if (rfilter != \"\") { if (rfilter == \"light\") { if ( (dType != pTypeLighting1) && (dType != pTypeLighting2) && (dType != pTypeLighting3) && (dType != pTypeLighting4) && (dType != pTypeLighting5) && (dType != pTypeLighting6) && (dType != pTypeFan) && (dType != pTypeColorSwitch) && (dType != pTypeSecurity1) && (dType != pTypeSecurity2) && (dType != pTypeEvohome) && (dType != pTypeEvohomeRelay) && (dType != pTypeCurtain) && (dType != pTypeBlinds) && (dType != pTypeRFY) && (dType != pTypeChime) && (dType != pTypeThermostat2) && (dType != pTypeThermostat3) && (dType != pTypeThermostat4) && (dType != pTypeRemote) && (dType != pTypeGeneralSwitch) && (dType != pTypeHomeConfort) && (dType != pTypeChime) && (dType != pTypeFS20) && (!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))) && (!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator))) ) continue; } else if (rfilter == \"temp\") { if ( (dType != pTypeTEMP) && (dType != pTypeHUM) && (dType != pTypeTEMP_HUM) && (dType != pTypeTEMP_HUM_BARO) && (dType != pTypeTEMP_BARO) && (dType != pTypeEvohomeZone) && (dType != pTypeEvohomeWater) && (!((dType == pTypeWIND) && (dSubType == sTypeWIND4))) && (!((dType == pTypeUV) && (dSubType == sTypeUV3))) && (!((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp))) && (dType != pTypeThermostat1) && (!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))) && (dType != pTypeRego6XXTemp) ) continue; } else if (rfilter == \"weather\") { if ( (dType != pTypeWIND) && (dType != pTypeRAIN) && (dType != pTypeTEMP_HUM_BARO) && (dType != pTypeTEMP_BARO) && (dType != pTypeUV) && (!((dType == pTypeGeneral) && (dSubType == sTypeVisibility))) && (!((dType == pTypeGeneral) && (dSubType == sTypeBaro))) && (!((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation))) ) continue; } else if (rfilter == \"utility\") { if ( (dType != pTypeRFXMeter) && (!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorAD))) && (!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorVolt))) && (!((dType == pTypeGeneral) && (dSubType == sTypeVoltage))) && (!((dType == pTypeGeneral) && (dSubType == sTypeCurrent))) && (!((dType == pTypeGeneral) && (dSubType == sTypeTextStatus))) && (!((dType == pTypeGeneral) && (dSubType == sTypeAlert))) && (!((dType == pTypeGeneral) && (dSubType == sTypePressure))) && (!((dType == pTypeGeneral) && (dSubType == sTypeSoilMoisture))) && (!((dType == pTypeGeneral) && (dSubType == sTypeLeafWetness))) && (!((dType == pTypeGeneral) && (dSubType == sTypePercentage))) && (!((dType == pTypeGeneral) && (dSubType == sTypeWaterflow))) && (!((dType == pTypeGeneral) && (dSubType == sTypeCustom))) && (!((dType == pTypeGeneral) && (dSubType == sTypeFan))) && (!((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))) && (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveClock))) && (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatMode))) && (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatFanMode))) && (!((dType == pTypeGeneral) && (dSubType == sTypeDistance))) && (!((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental))) && (!((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter))) && (!((dType == pTypeGeneral) && (dSubType == sTypeKwh))) && (dType != pTypeCURRENT) && (dType != pTypeCURRENTENERGY) && (dType != pTypeENERGY) && (dType != pTypePOWER) && (dType != pTypeP1Power) && (dType != pTypeP1Gas) && (dType != pTypeYouLess) && (dType != pTypeAirQuality) && (dType != pTypeLux) && (dType != pTypeUsage) && (!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))) && (!((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint))) && (dType != pTypeWEIGHT) && (!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwares))) ) continue; } else if (rfilter == \"wind\") { if ( (dType != pTypeWIND) ) continue; } else if (rfilter == \"rain\") { if ( (dType != pTypeRAIN) ) continue; } else if (rfilter == \"uv\") { if ( (dType != pTypeUV) ) continue; } else if (rfilter == \"baro\") { if ( (dType != pTypeTEMP_HUM_BARO) && (dType != pTypeTEMP_BARO) ) continue; } else if (rfilter == \"zwavealarms\") { if (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveAlarm))) continue; } } std::string thisIdx = sd[0]; int devIdx = atoi(thisIdx.c_str()); if ((ii > 0) && thisIdx == root[\"result\"][ii - 1][\"idx\"].asString()) { std::string typeOfThisOne = RFX_Type_Desc(dType, 1); if (typeOfThisOne == root[\"result\"][ii - 1][\"Type\"].asString()) { root[\"result\"][ii - 1][\"PlanIDs\"].append(atoi(sd[26].c_str())); continue; } } root[\"result\"][ii][\"HardwareID\"] = hardwareID; if (_hardwareNames.find(hardwareID) == _hardwareNames.end()) { root[\"result\"][ii][\"HardwareName\"] = \"Unknown?\"; root[\"result\"][ii][\"HardwareTypeVal\"] = 0; root[\"result\"][ii][\"HardwareType\"] = \"Unknown?\"; } else { root[\"result\"][ii][\"HardwareName\"] = _hardwareNames[hardwareID].Name; root[\"result\"][ii][\"HardwareTypeVal\"] = _hardwareNames[hardwareID].HardwareTypeVal; root[\"result\"][ii][\"HardwareType\"] = _hardwareNames[hardwareID].HardwareType; } root[\"result\"][ii][\"idx\"] = sd[0]; root[\"result\"][ii][\"Protected\"] = (iProtected != 0); CDomoticzHardwareBase *pHardware = m_mainworker.GetHardware(hardwareID); if (pHardware != NULL) { if (pHardware->HwdType == HTYPE_SolarEdgeAPI) { int seSensorTimeOut = 60 * 24 * 60; bHaveTimeout = (now - checktime >= seSensorTimeOut * 60); } else if (pHardware->HwdType == HTYPE_Wunderground) { CWunderground *pWHardware = reinterpret_cast(pHardware); std::string forecast_url = pWHardware->GetForecastURL(); if (forecast_url != \"\") { root[\"result\"][ii][\"forecast_url\"] = base64_encode(forecast_url); } } else if (pHardware->HwdType == HTYPE_DarkSky) { CDarkSky *pWHardware = reinterpret_cast(pHardware); std::string forecast_url = pWHardware->GetForecastURL(); if (forecast_url != \"\") { root[\"result\"][ii][\"forecast_url\"] = base64_encode(forecast_url); } } else if (pHardware->HwdType == HTYPE_AccuWeather) { CAccuWeather *pWHardware = reinterpret_cast(pHardware); std::string forecast_url = pWHardware->GetForecastURL(); if (forecast_url != \"\") { root[\"result\"][ii][\"forecast_url\"] = base64_encode(forecast_url); } } else if (pHardware->HwdType == HTYPE_OpenWeatherMap) { COpenWeatherMap *pWHardware = reinterpret_cast(pHardware); std::string forecast_url = pWHardware->GetForecastURL(); if (forecast_url != \"\") { root[\"result\"][ii][\"forecast_url\"] = base64_encode(forecast_url); } } } if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_PythonPlugin)) { root[\"result\"][ii][\"ID\"] = sd[1]; } else { sprintf(szData, \"%04X\", (unsigned int)atoi(sd[1].c_str())); if ( (dType == pTypeTEMP) || (dType == pTypeTEMP_BARO) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeBARO) || (dType == pTypeHUM) || (dType == pTypeWIND) || (dType == pTypeRAIN) || (dType == pTypeUV) || (dType == pTypeCURRENT) || (dType == pTypeCURRENTENERGY) || (dType == pTypeENERGY) || (dType == pTypeRFXMeter) || (dType == pTypeAirQuality) || (dType == pTypeRFXSensor) || (dType == pTypeP1Power) || (dType == pTypeP1Gas) ) { root[\"result\"][ii][\"ID\"] = szData; } else { root[\"result\"][ii][\"ID\"] = sd[1]; } } root[\"result\"][ii][\"Unit\"] = atoi(sd[2].c_str()); root[\"result\"][ii][\"Type\"] = RFX_Type_Desc(dType, 1); root[\"result\"][ii][\"SubType\"] = RFX_Type_SubType_Desc(dType, dSubType); root[\"result\"][ii][\"TypeImg\"] = RFX_Type_Desc(dType, 2); root[\"result\"][ii][\"Name\"] = sDeviceName; root[\"result\"][ii][\"Description\"] = Description; root[\"result\"][ii][\"Used\"] = used; root[\"result\"][ii][\"Favorite\"] = favorite; int iSignalLevel = atoi(sd[7].c_str()); if (iSignalLevel < 12) root[\"result\"][ii][\"SignalLevel\"] = iSignalLevel; else root[\"result\"][ii][\"SignalLevel\"] = \"-\"; root[\"result\"][ii][\"BatteryLevel\"] = atoi(sd[8].c_str()); root[\"result\"][ii][\"LastUpdate\"] = sLastUpdate; root[\"result\"][ii][\"CustomImage\"] = CustomImage; root[\"result\"][ii][\"XOffset\"] = sd[24].c_str(); root[\"result\"][ii][\"YOffset\"] = sd[25].c_str(); root[\"result\"][ii][\"PlanID\"] = sd[26].c_str(); Json::Value jsonArray; jsonArray.append(atoi(sd[26].c_str())); root[\"result\"][ii][\"PlanIDs\"] = jsonArray; root[\"result\"][ii][\"AddjValue\"] = AddjValue; root[\"result\"][ii][\"AddjMulti\"] = AddjMulti; root[\"result\"][ii][\"AddjValue2\"] = AddjValue2; root[\"result\"][ii][\"AddjMulti2\"] = AddjMulti2; std::stringstream s_data; s_data << int(nValue) << \", \" << sValue; root[\"result\"][ii][\"Data\"] = s_data.str(); root[\"result\"][ii][\"Notifications\"] = (m_notifications.HasNotifications(sd[0]) == true) ? \"true\" : \"false\"; root[\"result\"][ii][\"ShowNotifications\"] = true; bool bHasTimers = false; if ( (dType == pTypeLighting1) || (dType == pTypeLighting2) || (dType == pTypeLighting3) || (dType == pTypeLighting4) || (dType == pTypeLighting5) || (dType == pTypeLighting6) || (dType == pTypeFan) || (dType == pTypeColorSwitch) || (dType == pTypeCurtain) || (dType == pTypeBlinds) || (dType == pTypeRFY) || (dType == pTypeChime) || (dType == pTypeThermostat2) || (dType == pTypeThermostat3) || (dType == pTypeThermostat4) || (dType == pTypeRemote) || (dType == pTypeGeneralSwitch) || (dType == pTypeHomeConfort) || (dType == pTypeFS20) || ((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)) || ((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus)) ) { bHasTimers = m_sql.HasTimers(sd[0]); bHaveTimeout = false; #ifdef WITH_OPENZWAVE if (pHardware != NULL) { if (pHardware->HwdType == HTYPE_OpenZWave) { COpenZWave *pZWave = reinterpret_cast(pHardware); unsigned long ID; std::stringstream s_strid; s_strid << std::hex << sd[1]; s_strid >> ID; int nodeID = (ID & 0x0000FF00) >> 8; bHaveTimeout = pZWave->HasNodeFailed(nodeID); } } #endif root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; std::string lstatus = \"\"; int llevel = 0; bool bHaveDimmer = false; bool bHaveGroupCmd = false; int maxDimLevel = 0; GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd); root[\"result\"][ii][\"Status\"] = lstatus; root[\"result\"][ii][\"StrParam1\"] = strParam1; root[\"result\"][ii][\"StrParam2\"] = strParam2; std::string IconFile = \"Light\"; std::map::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage); if (ittIcon != m_custom_light_icons_lookup.end()) { IconFile = m_custom_light_icons[ittIcon->second].RootFile; } root[\"result\"][ii][\"Image\"] = IconFile; if (switchtype == STYPE_Dimmer) { root[\"result\"][ii][\"Level\"] = LastLevel; int iLevel = round((float(maxDimLevel) \/ 100.0f)*LastLevel); root[\"result\"][ii][\"LevelInt\"] = iLevel; if ((dType == pTypeColorSwitch) || (dType == pTypeLighting5 && dSubType == sTypeTRC02) || (dType == pTypeLighting5 && dSubType == sTypeTRC02_2) || (dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02) || (dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02_2)) { _tColor color(sColor); std::string jsonColor = color.toJSONString(); root[\"result\"][ii][\"Color\"] = jsonColor; llevel = LastLevel; if (lstatus == \"Set Level\" || lstatus == \"Set Color\") { sprintf(szTmp, \"Set Level: %d %%\", LastLevel); root[\"result\"][ii][\"Status\"] = szTmp; } } } else { root[\"result\"][ii][\"Level\"] = llevel; root[\"result\"][ii][\"LevelInt\"] = atoi(sValue.c_str()); } root[\"result\"][ii][\"HaveDimmer\"] = bHaveDimmer; std::string DimmerType = \"none\"; if (switchtype == STYPE_Dimmer) { DimmerType = \"abs\"; if (_hardwareNames.find(hardwareID) != _hardwareNames.end()) { if (_hardwareNames[hardwareID].HardwareTypeVal == HTYPE_LimitlessLights && atoi(_hardwareNames[hardwareID].Mode2.c_str()) != CLimitLess::LBTYPE_V6 && (atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_RGB || atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_White || atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_CW_WW)) { DimmerType = \"rel\"; } } } root[\"result\"][ii][\"DimmerType\"] = DimmerType; root[\"result\"][ii][\"MaxDimLevel\"] = maxDimLevel; root[\"result\"][ii][\"HaveGroupCmd\"] = bHaveGroupCmd; root[\"result\"][ii][\"SwitchType\"] = Switch_Type_Desc(switchtype); root[\"result\"][ii][\"SwitchTypeVal\"] = switchtype; uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]); root[\"result\"][ii][\"UsedByCamera\"] = (camIDX != 0) ? true : false; if (camIDX != 0) { std::stringstream scidx; scidx << camIDX; root[\"result\"][ii][\"CameraIdx\"] = scidx.str(); } bool bIsSubDevice = false; std::vector > resultSD; resultSD = m_sql.safe_query(\"SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q')\", sd[0].c_str()); bIsSubDevice = (resultSD.size() > 0); root[\"result\"][ii][\"IsSubDevice\"] = bIsSubDevice; if (switchtype == STYPE_Doorbell) { root[\"result\"][ii][\"TypeImg\"] = \"doorbell\"; root[\"result\"][ii][\"Status\"] = \"\";\/\/\"Pressed\"; } else if (switchtype == STYPE_DoorContact) { if (CustomImage == 0) { root[\"result\"][ii][\"Image\"] = \"Door\"; } root[\"result\"][ii][\"TypeImg\"] = \"door\"; bool bIsOn = IsLightSwitchOn(lstatus); root[\"result\"][ii][\"InternalState\"] = (bIsOn == true) ? \"Open\" : \"Closed\"; if (bIsOn) { lstatus = \"Open\"; } else { lstatus = \"Closed\"; } root[\"result\"][ii][\"Status\"] = lstatus; } else if (switchtype == STYPE_DoorLock) { if (CustomImage == 0) { root[\"result\"][ii][\"Image\"] = \"Door\"; } root[\"result\"][ii][\"TypeImg\"] = \"door\"; bool bIsOn = IsLightSwitchOn(lstatus); root[\"result\"][ii][\"InternalState\"] = (bIsOn == true) ? \"Locked\" : \"Unlocked\"; if (bIsOn) { lstatus = \"Locked\"; } else { lstatus = \"Unlocked\"; } root[\"result\"][ii][\"Status\"] = lstatus; } else if (switchtype == STYPE_DoorLockInverted) { if (CustomImage == 0) { root[\"result\"][ii][\"Image\"] = \"Door\"; } root[\"result\"][ii][\"TypeImg\"] = \"door\"; bool bIsOn = IsLightSwitchOn(lstatus); root[\"result\"][ii][\"InternalState\"] = (bIsOn == true) ? \"Unlocked\" : \"Locked\"; if (bIsOn) { lstatus = \"Unlocked\"; } else { lstatus = \"Locked\"; } root[\"result\"][ii][\"Status\"] = lstatus; } else if (switchtype == STYPE_PushOn) { if (CustomImage == 0) { root[\"result\"][ii][\"Image\"] = \"Push\"; } root[\"result\"][ii][\"TypeImg\"] = \"push\"; root[\"result\"][ii][\"Status\"] = \"\"; root[\"result\"][ii][\"InternalState\"] = (IsLightSwitchOn(lstatus) == true) ? \"On\" : \"Off\"; } else if (switchtype == STYPE_PushOff) { if (CustomImage == 0) { root[\"result\"][ii][\"Image\"] = \"Push\"; } root[\"result\"][ii][\"TypeImg\"] = \"push\"; root[\"result\"][ii][\"Status\"] = \"\"; root[\"result\"][ii][\"TypeImg\"] = \"pushoff\"; } else if (switchtype == STYPE_X10Siren) root[\"result\"][ii][\"TypeImg\"] = \"siren\"; else if (switchtype == STYPE_SMOKEDETECTOR) { root[\"result\"][ii][\"TypeImg\"] = \"smoke\"; root[\"result\"][ii][\"SwitchTypeVal\"] = STYPE_SMOKEDETECTOR; root[\"result\"][ii][\"SwitchType\"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR); } else if (switchtype == STYPE_Contact) { if (CustomImage == 0) { root[\"result\"][ii][\"Image\"] = \"Contact\"; } root[\"result\"][ii][\"TypeImg\"] = \"contact\"; bool bIsOn = IsLightSwitchOn(lstatus); if (bIsOn) { lstatus = \"Open\"; } else { lstatus = \"Closed\"; } root[\"result\"][ii][\"Status\"] = lstatus; } else if (switchtype == STYPE_Media) { if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_LogitechMediaServer)) root[\"result\"][ii][\"TypeImg\"] = \"LogitechMediaServer\"; else root[\"result\"][ii][\"TypeImg\"] = \"Media\"; root[\"result\"][ii][\"Status\"] = Media_Player_States((_eMediaStatus)nValue); lstatus = sValue; } else if ( (switchtype == STYPE_Blinds) || (switchtype == STYPE_VenetianBlindsUS) || (switchtype == STYPE_VenetianBlindsEU) ) { root[\"result\"][ii][\"TypeImg\"] = \"blinds\"; if ((lstatus == \"On\") || (lstatus == \"Close inline relay\")) { lstatus = \"Closed\"; } else if ((lstatus == \"Stop\") || (lstatus == \"Stop inline relay\")) { lstatus = \"Stopped\"; } else { lstatus = \"Open\"; } root[\"result\"][ii][\"Status\"] = lstatus; } else if (switchtype == STYPE_BlindsInverted) { root[\"result\"][ii][\"TypeImg\"] = \"blinds\"; if (lstatus == \"On\") { lstatus = \"Open\"; } else { lstatus = \"Closed\"; } root[\"result\"][ii][\"Status\"] = lstatus; } else if ((switchtype == STYPE_BlindsPercentage) || (switchtype == STYPE_BlindsPercentageInverted)) { root[\"result\"][ii][\"TypeImg\"] = \"blinds\"; root[\"result\"][ii][\"Level\"] = LastLevel; int iLevel = round((float(maxDimLevel) \/ 100.0f)*LastLevel); root[\"result\"][ii][\"LevelInt\"] = iLevel; if (lstatus == \"On\") { lstatus = (switchtype == STYPE_BlindsPercentage) ? \"Closed\" : \"Open\"; } else if (lstatus == \"Off\") { lstatus = (switchtype == STYPE_BlindsPercentage) ? \"Open\" : \"Closed\"; } root[\"result\"][ii][\"Status\"] = lstatus; } else if (switchtype == STYPE_Dimmer) { root[\"result\"][ii][\"TypeImg\"] = \"dimmer\"; } else if (switchtype == STYPE_Motion) { root[\"result\"][ii][\"TypeImg\"] = \"motion\"; } else if (switchtype == STYPE_Selector) { std::string selectorStyle = options[\"SelectorStyle\"]; std::string levelOffHidden = options[\"LevelOffHidden\"]; std::string levelNames = options[\"LevelNames\"]; std::string levelActions = options[\"LevelActions\"]; if (selectorStyle.empty()) { selectorStyle.assign(\"0\"); \/\/ default is 'button set' } if (levelOffHidden.empty()) { levelOffHidden.assign(\"false\"); \/\/ default is 'not hidden' } if (levelNames.empty()) { levelNames.assign(\"Off\"); \/\/ default is Off only } root[\"result\"][ii][\"TypeImg\"] = \"Light\"; root[\"result\"][ii][\"SelectorStyle\"] = atoi(selectorStyle.c_str()); root[\"result\"][ii][\"LevelOffHidden\"] = (levelOffHidden == \"true\"); root[\"result\"][ii][\"LevelNames\"] = base64_encode(levelNames); root[\"result\"][ii][\"LevelActions\"] = base64_encode(levelActions); } sprintf(szData, \"%s\", lstatus.c_str()); root[\"result\"][ii][\"Data\"] = szData; } else if (dType == pTypeSecurity1) { std::string lstatus = \"\"; int llevel = 0; bool bHaveDimmer = false; bool bHaveGroupCmd = false; int maxDimLevel = 0; GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd); root[\"result\"][ii][\"Status\"] = lstatus; root[\"result\"][ii][\"HaveDimmer\"] = bHaveDimmer; root[\"result\"][ii][\"MaxDimLevel\"] = maxDimLevel; root[\"result\"][ii][\"HaveGroupCmd\"] = bHaveGroupCmd; root[\"result\"][ii][\"SwitchType\"] = \"Security\"; root[\"result\"][ii][\"SwitchTypeVal\"] = switchtype; \/\/was 0?; root[\"result\"][ii][\"TypeImg\"] = \"security\"; root[\"result\"][ii][\"StrParam1\"] = strParam1; root[\"result\"][ii][\"StrParam2\"] = strParam2; root[\"result\"][ii][\"Protected\"] = (iProtected != 0); if ((dSubType == sTypeKD101) || (dSubType == sTypeSA30) || (switchtype == STYPE_SMOKEDETECTOR)) { root[\"result\"][ii][\"SwitchTypeVal\"] = STYPE_SMOKEDETECTOR; root[\"result\"][ii][\"TypeImg\"] = \"smoke\"; root[\"result\"][ii][\"SwitchType\"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR); } sprintf(szData, \"%s\", lstatus.c_str()); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = false; } else if (dType == pTypeSecurity2) { std::string lstatus = \"\"; int llevel = 0; bool bHaveDimmer = false; bool bHaveGroupCmd = false; int maxDimLevel = 0; GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd); root[\"result\"][ii][\"Status\"] = lstatus; root[\"result\"][ii][\"HaveDimmer\"] = bHaveDimmer; root[\"result\"][ii][\"MaxDimLevel\"] = maxDimLevel; root[\"result\"][ii][\"HaveGroupCmd\"] = bHaveGroupCmd; root[\"result\"][ii][\"SwitchType\"] = \"Security\"; root[\"result\"][ii][\"SwitchTypeVal\"] = switchtype; \/\/was 0?; root[\"result\"][ii][\"TypeImg\"] = \"security\"; root[\"result\"][ii][\"StrParam1\"] = strParam1; root[\"result\"][ii][\"StrParam2\"] = strParam2; root[\"result\"][ii][\"Protected\"] = (iProtected != 0); sprintf(szData, \"%s\", lstatus.c_str()); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = false; } else if (dType == pTypeEvohome || dType == pTypeEvohomeRelay) { std::string lstatus = \"\"; int llevel = 0; bool bHaveDimmer = false; bool bHaveGroupCmd = false; int maxDimLevel = 0; GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd); root[\"result\"][ii][\"Status\"] = lstatus; root[\"result\"][ii][\"HaveDimmer\"] = bHaveDimmer; root[\"result\"][ii][\"MaxDimLevel\"] = maxDimLevel; root[\"result\"][ii][\"HaveGroupCmd\"] = bHaveGroupCmd; root[\"result\"][ii][\"SwitchType\"] = \"evohome\"; root[\"result\"][ii][\"SwitchTypeVal\"] = switchtype; \/\/was 0?; root[\"result\"][ii][\"TypeImg\"] = \"override_mini\"; root[\"result\"][ii][\"StrParam1\"] = strParam1; root[\"result\"][ii][\"StrParam2\"] = strParam2; root[\"result\"][ii][\"Protected\"] = (iProtected != 0); sprintf(szData, \"%s\", lstatus.c_str()); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = false; if (dType == pTypeEvohomeRelay) { root[\"result\"][ii][\"SwitchType\"] = \"TPI\"; root[\"result\"][ii][\"Level\"] = llevel; root[\"result\"][ii][\"LevelInt\"] = atoi(sValue.c_str()); if (root[\"result\"][ii][\"Unit\"].asInt() > 100) root[\"result\"][ii][\"Protected\"] = true; sprintf(szData, \"%s: %d\", lstatus.c_str(), atoi(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; } } else if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)) { root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"TypeImg\"] = \"override_mini\"; std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() >= 3) { int i = 0; double tempCelcius = atof(strarray[i++].c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); double tempSetPoint; root[\"result\"][ii][\"Temp\"] = temp; if (dType == pTypeEvohomeZone) { tempCelcius = atof(strarray[i++].c_str()); tempSetPoint = ConvertTemperature(tempCelcius, tempsign); root[\"result\"][ii][\"SetPoint\"] = tempSetPoint; } else root[\"result\"][ii][\"State\"] = strarray[i++]; std::string strstatus = strarray[i++]; root[\"result\"][ii][\"Status\"] = strstatus; if ((dType == pTypeEvohomeZone || dType == pTypeEvohomeWater) && strarray.size() >= 4) { root[\"result\"][ii][\"Until\"] = strarray[i++]; } if (dType == pTypeEvohomeZone) { if (tempCelcius == 325.1) sprintf(szTmp, \"Off\"); else sprintf(szTmp, \"%.1f %c\", tempSetPoint, tempsign); if (strarray.size() >= 4) sprintf(szData, \"%.1f %c, (%s), %s until %s\", temp, tempsign, szTmp, strstatus.c_str(), strarray[3].c_str()); else sprintf(szData, \"%.1f %c, (%s), %s\", temp, tempsign, szTmp, strstatus.c_str()); } else if (strarray.size() >= 4) sprintf(szData, \"%.1f %c, %s, %s until %s\", temp, tempsign, strarray[1].c_str(), strstatus.c_str(), strarray[3].c_str()); else sprintf(szData, \"%.1f %c, %s, %s\", temp, tempsign, strarray[1].c_str(), strstatus.c_str()); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } } else if ((dType == pTypeTEMP) || (dType == pTypeRego6XXTemp)) { double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign); root[\"result\"][ii][\"Temp\"] = tvalue; sprintf(szData, \"%.1f %c\", tvalue, tempsign); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root[\"result\"][ii][\"trend\"] = (int)tstate; } else if (dType == pTypeThermostat1) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() == 4) { double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign); root[\"result\"][ii][\"Temp\"] = tvalue; sprintf(szData, \"%.1f %c\", tvalue, tempsign); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } } else if ((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) { double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign); root[\"result\"][ii][\"Temp\"] = tvalue; sprintf(szData, \"%.1f %c\", tvalue, tempsign); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"TypeImg\"] = \"temperature\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root[\"result\"][ii][\"trend\"] = (int)tstate; } else if (dType == pTypeHUM) { root[\"result\"][ii][\"Humidity\"] = nValue; root[\"result\"][ii][\"HumidityStatus\"] = RFX_Humidity_Status_Desc(atoi(sValue.c_str())); sprintf(szData, \"Humidity %d %%\", nValue); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } else if (dType == pTypeTEMP_HUM) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() == 3) { double tempCelcius = atof(strarray[0].c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); int humidity = atoi(strarray[1].c_str()); root[\"result\"][ii][\"Temp\"] = temp; root[\"result\"][ii][\"Humidity\"] = humidity; root[\"result\"][ii][\"HumidityStatus\"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str())); sprintf(szData, \"%.1f %c, %d %%\", temp, tempsign, atoi(strarray[1].c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; sprintf(szTmp, \"%.2f\", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign)); root[\"result\"][ii][\"DewPoint\"] = szTmp; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root[\"result\"][ii][\"trend\"] = (int)tstate; } } else if (dType == pTypeTEMP_HUM_BARO) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() == 5) { double tempCelcius = atof(strarray[0].c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); int humidity = atoi(strarray[1].c_str()); root[\"result\"][ii][\"Temp\"] = temp; root[\"result\"][ii][\"Humidity\"] = humidity; root[\"result\"][ii][\"HumidityStatus\"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str())); root[\"result\"][ii][\"Forecast\"] = atoi(strarray[4].c_str()); sprintf(szTmp, \"%.2f\", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign)); root[\"result\"][ii][\"DewPoint\"] = szTmp; if (dSubType == sTypeTHBFloat) { root[\"result\"][ii][\"Barometer\"] = atof(strarray[3].c_str()); root[\"result\"][ii][\"ForecastStr\"] = RFX_WSForecast_Desc(atoi(strarray[4].c_str())); } else { root[\"result\"][ii][\"Barometer\"] = atoi(strarray[3].c_str()); root[\"result\"][ii][\"ForecastStr\"] = RFX_Forecast_Desc(atoi(strarray[4].c_str())); } if (dSubType == sTypeTHBFloat) { sprintf(szData, \"%.1f %c, %d %%, %.1f hPa\", temp, tempsign, atoi(strarray[1].c_str()), atof(strarray[3].c_str()) ); } else { sprintf(szData, \"%.1f %c, %d %%, %d hPa\", temp, tempsign, atoi(strarray[1].c_str()), atoi(strarray[3].c_str()) ); } root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root[\"result\"][ii][\"trend\"] = (int)tstate; } } else if (dType == pTypeTEMP_BARO) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() >= 3) { double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign); root[\"result\"][ii][\"Temp\"] = tvalue; int forecast = atoi(strarray[2].c_str()); root[\"result\"][ii][\"Forecast\"] = forecast; root[\"result\"][ii][\"ForecastStr\"] = BMP_Forecast_Desc(forecast); root[\"result\"][ii][\"Barometer\"] = atof(strarray[1].c_str()); sprintf(szData, \"%.1f %c, %.1f hPa\", tvalue, tempsign, atof(strarray[1].c_str()) ); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root[\"result\"][ii][\"trend\"] = (int)tstate; } } else if (dType == pTypeUV) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() == 2) { float UVI = static_cast(atof(strarray[0].c_str())); root[\"result\"][ii][\"UVI\"] = strarray[0]; if (dSubType == sTypeUV3) { double tvalue = ConvertTemperature(atof(strarray[1].c_str()), tempsign); root[\"result\"][ii][\"Temp\"] = tvalue; sprintf(szData, \"%.1f UVI, %.1f° %c\", UVI, tvalue, tempsign); _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root[\"result\"][ii][\"trend\"] = (int)tstate; } else { sprintf(szData, \"%.1f UVI\", UVI); } root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } } else if (dType == pTypeWIND) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() == 6) { root[\"result\"][ii][\"Direction\"] = atof(strarray[0].c_str()); root[\"result\"][ii][\"DirectionStr\"] = strarray[1]; if (dSubType != sTypeWIND5) { int intSpeed = atoi(strarray[2].c_str()); if (m_sql.m_windunit != WINDUNIT_Beaufort) { sprintf(szTmp, \"%.1f\", float(intSpeed) * m_sql.m_windscale); } else { float windms = float(intSpeed) * 0.1f; sprintf(szTmp, \"%d\", MStoBeaufort(windms)); } root[\"result\"][ii][\"Speed\"] = szTmp; } { int intGust = atoi(strarray[3].c_str()); if (m_sql.m_windunit != WINDUNIT_Beaufort) { sprintf(szTmp, \"%.1f\", float(intGust) *m_sql.m_windscale); } else { float gustms = float(intGust) * 0.1f; sprintf(szTmp, \"%d\", MStoBeaufort(gustms)); } root[\"result\"][ii][\"Gust\"] = szTmp; } if ((dSubType == sTypeWIND4) || (dSubType == sTypeWINDNoTemp)) { if (dSubType == sTypeWIND4) { double tvalue = ConvertTemperature(atof(strarray[4].c_str()), tempsign); root[\"result\"][ii][\"Temp\"] = tvalue; } double tvalue = ConvertTemperature(atof(strarray[5].c_str()), tempsign); root[\"result\"][ii][\"Chill\"] = tvalue; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root[\"result\"][ii][\"trend\"] = (int)tstate; } root[\"result\"][ii][\"Data\"] = sValue; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } } else if (dType == pTypeRAIN) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() == 2) { time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, <ime); char szDate[40]; sprintf(szDate, \"%04d-%02d-%02d\", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector > result2; if (dSubType != sTypeRAINWU) { result2 = m_sql.safe_query( \"SELECT MIN(Total), MAX(Total) FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q')\", sd[0].c_str(), szDate); } else { result2 = m_sql.safe_query( \"SELECT Total, Total FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q') ORDER BY ROWID DESC LIMIT 1\", sd[0].c_str(), szDate); } if (!result2.empty()) { double total_real = 0; float rate = 0; std::vector sd2 = result2[0]; if (dSubType != sTypeRAINWU) { double total_min = atof(sd2[0].c_str()); double total_max = atof(strarray[1].c_str()); total_real = total_max - total_min; } else { total_real = atof(sd2[1].c_str()); } total_real *= AddjMulti; rate = (static_cast(atof(strarray[0].c_str())) \/ 100.0f)*float(AddjMulti); sprintf(szTmp, \"%.1f\", total_real); root[\"result\"][ii][\"Rain\"] = szTmp; sprintf(szTmp, \"%g\", rate); root[\"result\"][ii][\"RainRate\"] = szTmp; root[\"result\"][ii][\"Data\"] = sValue; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } else { root[\"result\"][ii][\"Rain\"] = \"0\"; root[\"result\"][ii][\"RainRate\"] = \"0\"; root[\"result\"][ii][\"Data\"] = \"0\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } } } else if (dType == pTypeRFXMeter) { std::string ValueQuantity = options[\"ValueQuantity\"]; std::string ValueUnits = options[\"ValueUnits\"]; if (ValueQuantity.empty()) { ValueQuantity.assign(\"Count\"); } if (ValueUnits.empty()) { ValueUnits.assign(\"\"); } time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, <ime); char szDate[40]; sprintf(szDate, \"%04d-%02d-%02d\", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector > result2; strcpy(szTmp, \"0\"); result2 = m_sql.safe_query(\"SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')\", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector sd2 = result2[0]; uint64_t total_min = std::stoull(sd2[0]); uint64_t total_max = std::stoull(sValue); uint64_t total_real = total_max - total_min; sprintf(szTmp, \"%\" PRIu64, total_real); float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); float musage = 0.0f; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(total_real) \/ divider; sprintf(szTmp, \"%.3f kWh\", musage); break; case MTYPE_GAS: musage = float(total_real) \/ divider; sprintf(szTmp, \"%.3f m3\", musage); break; case MTYPE_WATER: musage = float(total_real) \/ (divider \/ 1000.0f); sprintf(szTmp, \"%d Liter\", round(musage)); break; case MTYPE_COUNTER: sprintf(szTmp, \"%\" PRIu64, total_real); if (!ValueUnits.empty()) { strcat(szTmp, \" \"); strcat(szTmp, ValueUnits.c_str()); } break; default: strcpy(szTmp, \"?\"); break; } } root[\"result\"][ii][\"CounterToday\"] = szTmp; root[\"result\"][ii][\"SwitchTypeVal\"] = metertype; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"ValueQuantity\"] = \"\"; root[\"result\"][ii][\"ValueUnits\"] = \"\"; double meteroffset = AddjValue; float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); double dvalue = static_cast(atof(sValue.c_str())); switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: sprintf(szTmp, \"%.3f kWh\", meteroffset + (dvalue \/ divider)); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; break; case MTYPE_GAS: sprintf(szTmp, \"%.3f m3\", meteroffset + (dvalue \/ divider)); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; break; case MTYPE_WATER: sprintf(szTmp, \"%.3f m3\", meteroffset + (dvalue \/ divider)); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; break; case MTYPE_COUNTER: sprintf(szTmp, \"%g %s\", meteroffset + dvalue, ValueUnits.c_str()); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; root[\"result\"][ii][\"ValueQuantity\"] = ValueQuantity; root[\"result\"][ii][\"ValueUnits\"] = ValueUnits; break; default: root[\"result\"][ii][\"Data\"] = \"?\"; root[\"result\"][ii][\"Counter\"] = \"?\"; root[\"result\"][ii][\"ValueQuantity\"] = ValueQuantity; root[\"result\"][ii][\"ValueUnits\"] = ValueUnits; break; } } else if ((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental)) { std::string ValueQuantity = options[\"ValueQuantity\"]; std::string ValueUnits = options[\"ValueUnits\"]; if (ValueQuantity.empty()) { ValueQuantity.assign(\"Count\"); } if (ValueUnits.empty()) { ValueUnits.assign(\"\"); } float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, <ime); char szDate[40]; sprintf(szDate, \"%04d-%02d-%02d\", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector > result2; strcpy(szTmp, \"0\"); result2 = m_sql.safe_query(\"SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')\", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector sd2 = result2[0]; uint64_t total_min = std::stoull(sd2[0]); uint64_t total_max = std::stoull(sValue); uint64_t total_real = total_max - total_min; sprintf(szTmp, \"%\" PRIu64, total_real); float musage = 0; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(total_real) \/ divider; sprintf(szTmp, \"%.3f kWh\", musage); break; case MTYPE_GAS: musage = float(total_real) \/ divider; sprintf(szTmp, \"%.3f m3\", musage); break; case MTYPE_WATER: musage = float(total_real) \/ divider; sprintf(szTmp, \"%.3f m3\", musage); break; case MTYPE_COUNTER: sprintf(szTmp, \"%\" PRIu64, total_real); if (!ValueUnits.empty()) { strcat(szTmp, \" \"); strcat(szTmp, ValueUnits.c_str()); } break; default: strcpy(szTmp, \"0\"); break; } } root[\"result\"][ii][\"Counter\"] = sValue; root[\"result\"][ii][\"CounterToday\"] = szTmp; root[\"result\"][ii][\"SwitchTypeVal\"] = metertype; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"TypeImg\"] = \"counter\"; root[\"result\"][ii][\"ValueQuantity\"] = \"\"; root[\"result\"][ii][\"ValueUnits\"] = \"\"; double dvalue = static_cast(atof(sValue.c_str())); double meteroffset = AddjValue; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: sprintf(szTmp, \"%.3f kWh\", meteroffset + (dvalue \/ divider)); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; break; case MTYPE_GAS: sprintf(szTmp, \"%.3f m3\", meteroffset + (dvalue \/ divider)); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; break; case MTYPE_WATER: sprintf(szTmp, \"%.3f m3\", meteroffset + (dvalue \/ divider)); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; break; case MTYPE_COUNTER: sprintf(szTmp, \"%\" PRIu64 \" %s\", static_cast(meteroffset + dvalue), ValueUnits.c_str()); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; root[\"result\"][ii][\"ValueQuantity\"] = ValueQuantity; root[\"result\"][ii][\"ValueUnits\"] = ValueUnits; break; default: root[\"result\"][ii][\"Data\"] = \"?\"; root[\"result\"][ii][\"Counter\"] = \"?\"; root[\"result\"][ii][\"ValueQuantity\"] = ValueQuantity; root[\"result\"][ii][\"ValueUnits\"] = ValueUnits; break; } } else if ((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter)) { std::string ValueQuantity = options[\"ValueQuantity\"]; std::string ValueUnits = options[\"ValueUnits\"]; if (ValueQuantity.empty()) { ValueQuantity.assign(\"Count\"); } if (ValueUnits.empty()) { ValueUnits.assign(\"\"); } float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); std::vector splitresults; StringSplit(sValue, \";\", splitresults); double dvalue; if (splitresults.size() < 2) { dvalue = static_cast(atof(sValue.c_str())); } else { dvalue = static_cast(atof(splitresults[1].c_str())); if (dvalue < 0.0) { dvalue = static_cast(atof(splitresults[0].c_str())); } } root[\"result\"][ii][\"Data\"] = root[\"result\"][ii][\"Counter\"]; root[\"result\"][ii][\"SwitchTypeVal\"] = metertype; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"TypeImg\"] = \"counter\"; root[\"result\"][ii][\"ValueQuantity\"] = \"\"; root[\"result\"][ii][\"ValueUnits\"] = \"\"; root[\"result\"][ii][\"ShowNotifications\"] = false; double meteroffset = AddjValue; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: sprintf(szTmp, \"%.3f kWh\", meteroffset + (dvalue \/ divider)); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; break; case MTYPE_GAS: sprintf(szTmp, \"%.3f m3\", meteroffset + (dvalue \/ divider)); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; break; case MTYPE_WATER: sprintf(szTmp, \"%.3f m3\", meteroffset + (dvalue \/ divider)); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; break; case MTYPE_COUNTER: sprintf(szTmp, \"%g %s\", meteroffset + dvalue, ValueUnits.c_str()); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Counter\"] = szTmp; root[\"result\"][ii][\"ValueQuantity\"] = ValueQuantity; root[\"result\"][ii][\"ValueUnits\"] = ValueUnits; break; default: root[\"result\"][ii][\"Data\"] = \"?\"; root[\"result\"][ii][\"Counter\"] = \"?\"; root[\"result\"][ii][\"ValueQuantity\"] = ValueQuantity; root[\"result\"][ii][\"ValueUnits\"] = ValueUnits; break; } } else if (dType == pTypeYouLess) { std::string ValueQuantity = options[\"ValueQuantity\"]; std::string ValueUnits = options[\"ValueUnits\"]; float musage = 0; if (ValueQuantity.empty()) { ValueQuantity.assign(\"Count\"); } if (ValueUnits.empty()) { ValueUnits.assign(\"\"); } float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, <ime); char szDate[40]; sprintf(szDate, \"%04d-%02d-%02d\", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector > result2; strcpy(szTmp, \"0\"); result2 = m_sql.safe_query(\"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')\", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector sd2 = result2[0]; unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10); unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10); unsigned long long total_real; total_real = total_max - total_min; sprintf(szTmp, \"%llu\", total_real); musage = 0; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(total_real) \/ divider; sprintf(szTmp, \"%.3f kWh\", musage); break; case MTYPE_GAS: musage = float(total_real) \/ divider; sprintf(szTmp, \"%.3f m3\", musage); break; case MTYPE_WATER: musage = float(total_real) \/ divider; sprintf(szTmp, \"%.3f m3\", musage); break; case MTYPE_COUNTER: sprintf(szTmp, \"%llu %s\", total_real, ValueUnits.c_str()); break; default: strcpy(szTmp, \"0\"); break; } } root[\"result\"][ii][\"CounterToday\"] = szTmp; std::vector splitresults; StringSplit(sValue, \";\", splitresults); if (splitresults.size() < 2) continue; unsigned long long total_actual = std::strtoull(splitresults[0].c_str(), nullptr, 10); musage = 0; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(total_actual) \/ divider; sprintf(szTmp, \"%.03f\", musage); break; case MTYPE_GAS: case MTYPE_WATER: musage = float(total_actual) \/ divider; sprintf(szTmp, \"%.03f\", musage); break; case MTYPE_COUNTER: sprintf(szTmp, \"%llu\", total_actual); break; default: strcpy(szTmp, \"0\"); break; } root[\"result\"][ii][\"Counter\"] = szTmp; root[\"result\"][ii][\"SwitchTypeVal\"] = metertype; unsigned long long acounter = std::strtoull(sValue.c_str(), nullptr, 10); musage = 0; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(acounter) \/ divider; sprintf(szTmp, \"%.3f kWh %s Watt\", musage, splitresults[1].c_str()); break; case MTYPE_GAS: musage = float(acounter) \/ divider; sprintf(szTmp, \"%.3f m3\", musage); break; case MTYPE_WATER: musage = float(acounter) \/ divider; sprintf(szTmp, \"%.3f m3\", musage); break; case MTYPE_COUNTER: sprintf(szTmp, \"%llu %s\", acounter, ValueUnits.c_str()); break; default: strcpy(szTmp, \"0\"); break; } root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"ValueQuantity\"] = \"\"; root[\"result\"][ii][\"ValueUnits\"] = \"\"; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: sprintf(szTmp, \"%s Watt\", splitresults[1].c_str()); break; case MTYPE_GAS: sprintf(szTmp, \"%s m3\", splitresults[1].c_str()); break; case MTYPE_WATER: sprintf(szTmp, \"%s m3\", splitresults[1].c_str()); break; case MTYPE_COUNTER: sprintf(szTmp, \"%s\", splitresults[1].c_str()); root[\"result\"][ii][\"ValueQuantity\"] = ValueQuantity; root[\"result\"][ii][\"ValueUnits\"] = ValueUnits; break; default: strcpy(szTmp, \"0\"); break; } root[\"result\"][ii][\"Usage\"] = szTmp; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } else if (dType == pTypeP1Power) { std::vector splitresults; StringSplit(sValue, \";\", splitresults); if (splitresults.size() != 6) { root[\"result\"][ii][\"SwitchTypeVal\"] = MTYPE_ENERGY; root[\"result\"][ii][\"Counter\"] = \"0\"; root[\"result\"][ii][\"CounterDeliv\"] = \"0\"; root[\"result\"][ii][\"Usage\"] = \"Invalid\"; root[\"result\"][ii][\"UsageDeliv\"] = \"Invalid\"; root[\"result\"][ii][\"Data\"] = \"Invalid!: \" + sValue; root[\"result\"][ii][\"HaveTimeout\"] = true; root[\"result\"][ii][\"CounterToday\"] = \"Invalid\"; root[\"result\"][ii][\"CounterDelivToday\"] = \"Invalid\"; } else { float EnergyDivider = 1000.0f; int tValue; if (m_sql.GetPreferencesVar(\"MeterDividerEnergy\", tValue)) { EnergyDivider = float(tValue); } unsigned long long powerusage1 = std::strtoull(splitresults[0].c_str(), nullptr, 10); unsigned long long powerusage2 = std::strtoull(splitresults[1].c_str(), nullptr, 10); unsigned long long powerdeliv1 = std::strtoull(splitresults[2].c_str(), nullptr, 10); unsigned long long powerdeliv2 = std::strtoull(splitresults[3].c_str(), nullptr, 10); unsigned long long usagecurrent = std::strtoull(splitresults[4].c_str(), nullptr, 10); unsigned long long delivcurrent = std::strtoull(splitresults[5].c_str(), nullptr, 10); powerdeliv1 = (powerdeliv1 < 10) ? 0 : powerdeliv1; powerdeliv2 = (powerdeliv2 < 10) ? 0 : powerdeliv2; unsigned long long powerusage = powerusage1 + powerusage2; unsigned long long powerdeliv = powerdeliv1 + powerdeliv2; if (powerdeliv < 2) powerdeliv = 0; double musage = 0; root[\"result\"][ii][\"SwitchTypeVal\"] = MTYPE_ENERGY; musage = double(powerusage) \/ EnergyDivider; sprintf(szTmp, \"%.03f\", musage); root[\"result\"][ii][\"Counter\"] = szTmp; musage = double(powerdeliv) \/ EnergyDivider; sprintf(szTmp, \"%.03f\", musage); root[\"result\"][ii][\"CounterDeliv\"] = szTmp; if (bHaveTimeout) { usagecurrent = 0; delivcurrent = 0; } sprintf(szTmp, \"%llu Watt\", usagecurrent); root[\"result\"][ii][\"Usage\"] = szTmp; sprintf(szTmp, \"%llu Watt\", delivcurrent); root[\"result\"][ii][\"UsageDeliv\"] = szTmp; root[\"result\"][ii][\"Data\"] = sValue; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, <ime); char szDate[40]; sprintf(szDate, \"%04d-%02d-%02d\", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector > result2; strcpy(szTmp, \"0\"); result2 = m_sql.safe_query(\"SELECT MIN(Value1), MIN(Value2), MIN(Value5), MIN(Value6) FROM MultiMeter WHERE (DeviceRowID='%q' AND Date>='%q')\", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector sd2 = result2[0]; unsigned long long total_min_usage_1 = std::strtoull(sd2[0].c_str(), nullptr, 10); unsigned long long total_min_deliv_1 = std::strtoull(sd2[1].c_str(), nullptr, 10); unsigned long long total_min_usage_2 = std::strtoull(sd2[2].c_str(), nullptr, 10); unsigned long long total_min_deliv_2 = std::strtoull(sd2[3].c_str(), nullptr, 10); unsigned long long total_real_usage, total_real_deliv; total_real_usage = powerusage - (total_min_usage_1 + total_min_usage_2); total_real_deliv = powerdeliv - (total_min_deliv_1 + total_min_deliv_2); musage = double(total_real_usage) \/ EnergyDivider; sprintf(szTmp, \"%.3f kWh\", musage); root[\"result\"][ii][\"CounterToday\"] = szTmp; musage = double(total_real_deliv) \/ EnergyDivider; sprintf(szTmp, \"%.3f kWh\", musage); root[\"result\"][ii][\"CounterDelivToday\"] = szTmp; } else { sprintf(szTmp, \"%.3f kWh\", 0.0f); root[\"result\"][ii][\"CounterToday\"] = szTmp; root[\"result\"][ii][\"CounterDelivToday\"] = szTmp; } } } else if (dType == pTypeP1Gas) { root[\"result\"][ii][\"SwitchTypeVal\"] = MTYPE_GAS; time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, <ime); char szDate[40]; sprintf(szDate, \"%04d-%02d-%02d\", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector > result2; float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); strcpy(szTmp, \"0\"); result2 = m_sql.safe_query(\"SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')\", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector sd2 = result2[0]; uint64_t total_min_gas = std::stoull(sd2[0]); uint64_t gasactual = std::stoull(sValue); uint64_t total_real_gas = gasactual - total_min_gas; double musage = double(gasactual) \/ divider; sprintf(szTmp, \"%.03f\", musage); root[\"result\"][ii][\"Counter\"] = szTmp; musage = double(total_real_gas) \/ divider; sprintf(szTmp, \"%.03f m3\", musage); root[\"result\"][ii][\"CounterToday\"] = szTmp; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; sprintf(szTmp, \"%.03f\", atof(sValue.c_str()) \/ divider); root[\"result\"][ii][\"Data\"] = szTmp; } else { sprintf(szTmp, \"%.03f\", 0.0f); root[\"result\"][ii][\"Counter\"] = szTmp; sprintf(szTmp, \"%.03f m3\", 0.0f); root[\"result\"][ii][\"CounterToday\"] = szTmp; sprintf(szTmp, \"%.03f\", atof(sValue.c_str()) \/ divider); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } } else if (dType == pTypeCURRENT) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() == 3) { int displaytype = 0; int voltage = 230; m_sql.GetPreferencesVar(\"CM113DisplayType\", displaytype); m_sql.GetPreferencesVar(\"ElectricVoltage\", voltage); double val1 = atof(strarray[0].c_str()); double val2 = atof(strarray[1].c_str()); double val3 = atof(strarray[2].c_str()); if (displaytype == 0) { if ((val2 == 0) && (val3 == 0)) sprintf(szData, \"%.1f A\", val1); else sprintf(szData, \"%.1f A, %.1f A, %.1f A\", val1, val2, val3); } else { if ((val2 == 0) && (val3 == 0)) sprintf(szData, \"%d Watt\", int(val1*voltage)); else sprintf(szData, \"%d Watt, %d Watt, %d Watt\", int(val1*voltage), int(val2*voltage), int(val3*voltage)); } root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"displaytype\"] = displaytype; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } } else if (dType == pTypeCURRENTENERGY) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() == 4) { int displaytype = 0; int voltage = 230; m_sql.GetPreferencesVar(\"CM113DisplayType\", displaytype); m_sql.GetPreferencesVar(\"ElectricVoltage\", voltage); double total = atof(strarray[3].c_str()); if (displaytype == 0) { sprintf(szData, \"%.1f A, %.1f A, %.1f A\", atof(strarray[0].c_str()), atof(strarray[1].c_str()), atof(strarray[2].c_str())); } else { sprintf(szData, \"%d Watt, %d Watt, %d Watt\", int(atof(strarray[0].c_str())*voltage), int(atof(strarray[1].c_str())*voltage), int(atof(strarray[2].c_str())*voltage)); } if (total > 0) { sprintf(szTmp, \", Total: %.3f kWh\", total \/ 1000.0f); strcat(szData, szTmp); } root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"displaytype\"] = displaytype; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } } else if ( ((dType == pTypeENERGY) || (dType == pTypePOWER)) || ((dType == pTypeGeneral) && (dSubType == sTypeKwh)) ) { std::vector strarray; StringSplit(sValue, \";\", strarray); if (strarray.size() == 2) { double total = atof(strarray[1].c_str()) \/ 1000; time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, <ime); char szDate[40]; sprintf(szDate, \"%04d-%02d-%02d\", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector > result2; strcpy(szTmp, \"0\"); result2 = m_sql.safe_query(\"SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')\", sd[0].c_str(), szDate); if (!result2.empty()) { float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); std::vector sd2 = result2[0]; double minimum = atof(sd2[0].c_str()) \/ divider; sprintf(szData, \"%.3f kWh\", total); root[\"result\"][ii][\"Data\"] = szData; if ((dType == pTypeENERGY) || (dType == pTypePOWER)) { sprintf(szData, \"%ld Watt\", atol(strarray[0].c_str())); } else { sprintf(szData, \"%g Watt\", atof(strarray[0].c_str())); } root[\"result\"][ii][\"Usage\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; sprintf(szTmp, \"%.3f kWh\", total - minimum); root[\"result\"][ii][\"CounterToday\"] = szTmp; } else { sprintf(szData, \"%.3f kWh\", total); root[\"result\"][ii][\"Data\"] = szData; if ((dType == pTypeENERGY) || (dType == pTypePOWER)) { sprintf(szData, \"%ld Watt\", atol(strarray[0].c_str())); } else { sprintf(szData, \"%g Watt\", atof(strarray[0].c_str())); } root[\"result\"][ii][\"Usage\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; sprintf(szTmp, \"%d kWh\", 0); root[\"result\"][ii][\"CounterToday\"] = szTmp; } root[\"result\"][ii][\"TypeImg\"] = \"current\"; root[\"result\"][ii][\"SwitchTypeVal\"] = switchtype; \/\/MTYPE_ENERGY root[\"result\"][ii][\"EnergyMeterMode\"] = options[\"EnergyMeterMode\"]; \/\/for alternate Energy Reading } } else if (dType == pTypeAirQuality) { if (bHaveTimeout) nValue = 0; sprintf(szTmp, \"%d ppm\", nValue); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; int airquality = nValue; if (airquality < 700) root[\"result\"][ii][\"Quality\"] = \"Excellent\"; else if (airquality < 900) root[\"result\"][ii][\"Quality\"] = \"Good\"; else if (airquality < 1100) root[\"result\"][ii][\"Quality\"] = \"Fair\"; else if (airquality < 1600) root[\"result\"][ii][\"Quality\"] = \"Mediocre\"; else root[\"result\"][ii][\"Quality\"] = \"Bad\"; } else if (dType == pTypeThermostat) { if (dSubType == sTypeThermSetpoint) { bHasTimers = m_sql.HasTimers(sd[0]); double tempCelcius = atof(sValue.c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); sprintf(szTmp, \"%.1f\", temp); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"SetPoint\"] = szTmp; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"TypeImg\"] = \"override_mini\"; } } else if (dType == pTypeRadiator1) { if (dSubType == sTypeSmartwares) { bHasTimers = m_sql.HasTimers(sd[0]); double tempCelcius = atof(sValue.c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); sprintf(szTmp, \"%.1f\", temp); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"SetPoint\"] = szTmp; root[\"result\"][ii][\"HaveTimeout\"] = false; \/\/this device does not provide feedback, so no timeout! root[\"result\"][ii][\"TypeImg\"] = \"override_mini\"; } } else if (dType == pTypeGeneral) { if (dSubType == sTypeVisibility) { float vis = static_cast(atof(sValue.c_str())); if (metertype == 0) { sprintf(szTmp, \"%.1f km\", vis); } else { sprintf(szTmp, \"%.1f mi\", vis*0.6214f); } root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Visibility\"] = atof(sValue.c_str()); root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"TypeImg\"] = \"visibility\"; root[\"result\"][ii][\"SwitchTypeVal\"] = metertype; } else if (dSubType == sTypeDistance) { float vis = static_cast(atof(sValue.c_str())); if (metertype == 0) { sprintf(szTmp, \"%.1f cm\", vis); } else { sprintf(szTmp, \"%.1f in\", vis*0.6214f); } root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"TypeImg\"] = \"visibility\"; root[\"result\"][ii][\"SwitchTypeVal\"] = metertype; } else if (dSubType == sTypeSolarRadiation) { float radiation = static_cast(atof(sValue.c_str())); sprintf(szTmp, \"%.1f Watt\/m2\", radiation); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Radiation\"] = atof(sValue.c_str()); root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"TypeImg\"] = \"radiation\"; root[\"result\"][ii][\"SwitchTypeVal\"] = metertype; } else if (dSubType == sTypeSoilMoisture) { sprintf(szTmp, \"%d cb\", nValue); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"Desc\"] = Get_Moisture_Desc(nValue); root[\"result\"][ii][\"TypeImg\"] = \"moisture\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"SwitchTypeVal\"] = metertype; } else if (dSubType == sTypeLeafWetness) { sprintf(szTmp, \"%d\", nValue); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"TypeImg\"] = \"leaf\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"SwitchTypeVal\"] = metertype; } else if (dSubType == sTypeSystemTemp) { double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign); root[\"result\"][ii][\"Temp\"] = tvalue; sprintf(szData, \"%.1f %c\", tvalue, tempsign); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"Image\"] = \"Computer\"; root[\"result\"][ii][\"TypeImg\"] = \"temperature\"; root[\"result\"][ii][\"Type\"] = \"temperature\"; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root[\"result\"][ii][\"trend\"] = (int)tstate; } else if (dSubType == sTypePercentage) { sprintf(szData, \"%g%%\", atof(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"Image\"] = \"Computer\"; root[\"result\"][ii][\"TypeImg\"] = \"hardware\"; } else if (dSubType == sTypeWaterflow) { sprintf(szData, \"%g l\/min\", atof(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"Image\"] = \"Moisture\"; root[\"result\"][ii][\"TypeImg\"] = \"moisture\"; } else if (dSubType == sTypeCustom) { std::string szAxesLabel = \"\"; int SensorType = 1; std::vector sResults; StringSplit(sOptions, \";\", sResults); if (sResults.size() == 2) { SensorType = atoi(sResults[0].c_str()); szAxesLabel = sResults[1]; } sprintf(szData, \"%g %s\", atof(sValue.c_str()), szAxesLabel.c_str()); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"SensorType\"] = SensorType; root[\"result\"][ii][\"SensorUnit\"] = szAxesLabel; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; std::string IconFile = \"Custom\"; if (CustomImage != 0) { std::map::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage); if (ittIcon != m_custom_light_icons_lookup.end()) { IconFile = m_custom_light_icons[ittIcon->second].RootFile; } } root[\"result\"][ii][\"Image\"] = IconFile; root[\"result\"][ii][\"TypeImg\"] = IconFile; } else if (dSubType == sTypeFan) { sprintf(szData, \"%d RPM\", atoi(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"Image\"] = \"Fan\"; root[\"result\"][ii][\"TypeImg\"] = \"Fan\"; } else if (dSubType == sTypeSoundLevel) { sprintf(szData, \"%d dB\", atoi(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"TypeImg\"] = \"Speaker\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } else if (dSubType == sTypeVoltage) { sprintf(szData, \"%g V\", atof(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"TypeImg\"] = \"current\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"Voltage\"] = atof(sValue.c_str()); } else if (dSubType == sTypeCurrent) { sprintf(szData, \"%g A\", atof(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"TypeImg\"] = \"current\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"Current\"] = atof(sValue.c_str()); } else if (dSubType == sTypeTextStatus) { root[\"result\"][ii][\"Data\"] = sValue; root[\"result\"][ii][\"TypeImg\"] = \"text\"; root[\"result\"][ii][\"HaveTimeout\"] = false; root[\"result\"][ii][\"ShowNotifications\"] = false; } else if (dSubType == sTypeAlert) { if (nValue > 4) nValue = 4; sprintf(szData, \"Level: %d\", nValue); root[\"result\"][ii][\"Data\"] = szData; if (!sValue.empty()) root[\"result\"][ii][\"Data\"] = sValue; else root[\"result\"][ii][\"Data\"] = Get_Alert_Desc(nValue); root[\"result\"][ii][\"TypeImg\"] = \"Alert\"; root[\"result\"][ii][\"Level\"] = nValue; root[\"result\"][ii][\"HaveTimeout\"] = false; } else if (dSubType == sTypePressure) { sprintf(szData, \"%.1f Bar\", atof(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"TypeImg\"] = \"gauge\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"Pressure\"] = atof(sValue.c_str()); } else if (dSubType == sTypeBaro) { std::vector tstrarray; StringSplit(sValue, \";\", tstrarray); if (tstrarray.empty()) continue; sprintf(szData, \"%g hPa\", atof(tstrarray[0].c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"TypeImg\"] = \"gauge\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; if (tstrarray.size() > 1) { root[\"result\"][ii][\"Barometer\"] = atof(tstrarray[0].c_str()); int forecast = atoi(tstrarray[1].c_str()); root[\"result\"][ii][\"Forecast\"] = forecast; root[\"result\"][ii][\"ForecastStr\"] = BMP_Forecast_Desc(forecast); } } else if (dSubType == sTypeZWaveClock) { std::vector tstrarray; StringSplit(sValue, \";\", tstrarray); int day = 0; int hour = 0; int minute = 0; if (tstrarray.size() == 3) { day = atoi(tstrarray[0].c_str()); hour = atoi(tstrarray[1].c_str()); minute = atoi(tstrarray[2].c_str()); } sprintf(szData, \"%s %02d:%02d\", ZWave_Clock_Days(day), hour, minute); root[\"result\"][ii][\"DayTime\"] = sValue; root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"TypeImg\"] = \"clock\"; } else if (dSubType == sTypeZWaveThermostatMode) { strcpy(szData, \"\"); root[\"result\"][ii][\"Mode\"] = nValue; root[\"result\"][ii][\"TypeImg\"] = \"mode\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; std::string modes = \"\"; #ifdef WITH_OPENZWAVE if (pHardware) { if (pHardware->HwdType == HTYPE_OpenZWave) { COpenZWave *pZWave = reinterpret_cast(pHardware); unsigned long ID; std::stringstream s_strid; s_strid << std::hex << sd[1]; s_strid >> ID; std::vector vmodes = pZWave->GetSupportedThermostatModes(ID); int smode = 0; char szTmp[200]; for (const auto & itt : vmodes) { sprintf(szTmp, \"%d;%s;\", smode, itt.c_str()); modes += szTmp; smode++; } if (!vmodes.empty()) { if (nValue < (int)vmodes.size()) { sprintf(szData, \"%s\", vmodes[nValue].c_str()); } } } } #endif root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"Modes\"] = modes; } else if (dSubType == sTypeZWaveThermostatFanMode) { sprintf(szData, \"%s\", ZWave_Thermostat_Fan_Modes[nValue]); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"Mode\"] = nValue; root[\"result\"][ii][\"TypeImg\"] = \"mode\"; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; bool bAddedSupportedModes = false; std::string modes = \"\"; #ifdef WITH_OPENZWAVE if (pHardware) { if (pHardware->HwdType == HTYPE_OpenZWave) { COpenZWave *pZWave = reinterpret_cast(pHardware); unsigned long ID; std::stringstream s_strid; s_strid << std::hex << sd[1]; s_strid >> ID; modes = pZWave->GetSupportedThermostatFanModes(ID); bAddedSupportedModes = !modes.empty(); } } #endif if (!bAddedSupportedModes) { int smode = 0; while (ZWave_Thermostat_Fan_Modes[smode] != NULL) { sprintf(szTmp, \"%d;%s;\", smode, ZWave_Thermostat_Fan_Modes[smode]); modes += szTmp; smode++; } } root[\"result\"][ii][\"Modes\"] = modes; } else if (dSubType == sTypeZWaveAlarm) { sprintf(szData, \"Event: 0x%02X (%d)\", nValue, nValue); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"TypeImg\"] = \"Alert\"; root[\"result\"][ii][\"Level\"] = nValue; root[\"result\"][ii][\"HaveTimeout\"] = false; } } else if (dType == pTypeLux) { sprintf(szTmp, \"%.0f Lux\", atof(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } else if (dType == pTypeWEIGHT) { sprintf(szTmp, \"%g %s\", m_sql.m_weightscale * atof(sValue.c_str()), m_sql.m_weightsign.c_str()); root[\"result\"][ii][\"Data\"] = szTmp; root[\"result\"][ii][\"HaveTimeout\"] = false; } else if (dType == pTypeUsage) { if (dSubType == sTypeElectric) { sprintf(szData, \"%g Watt\", atof(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; } else { root[\"result\"][ii][\"Data\"] = sValue; } root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } else if (dType == pTypeRFXSensor) { switch (dSubType) { case sTypeRFXSensorAD: sprintf(szData, \"%d mV\", atoi(sValue.c_str())); root[\"result\"][ii][\"TypeImg\"] = \"current\"; break; case sTypeRFXSensorVolt: sprintf(szData, \"%d mV\", atoi(sValue.c_str())); root[\"result\"][ii][\"TypeImg\"] = \"current\"; break; } root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } else if (dType == pTypeRego6XXValue) { switch (dSubType) { case sTypeRego6XXStatus: { std::string lstatus = \"On\"; if (atoi(sValue.c_str()) == 0) { lstatus = \"Off\"; } root[\"result\"][ii][\"Status\"] = lstatus; root[\"result\"][ii][\"HaveDimmer\"] = false; root[\"result\"][ii][\"MaxDimLevel\"] = 0; root[\"result\"][ii][\"HaveGroupCmd\"] = false; root[\"result\"][ii][\"TypeImg\"] = \"utility\"; root[\"result\"][ii][\"SwitchTypeVal\"] = STYPE_OnOff; root[\"result\"][ii][\"SwitchType\"] = Switch_Type_Desc(STYPE_OnOff); sprintf(szData, \"%d\", atoi(sValue.c_str())); root[\"result\"][ii][\"Data\"] = szData; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; root[\"result\"][ii][\"StrParam1\"] = strParam1; root[\"result\"][ii][\"StrParam2\"] = strParam2; root[\"result\"][ii][\"Protected\"] = (iProtected != 0); if (CustomImage < static_cast(m_custom_light_icons.size())) root[\"result\"][ii][\"Image\"] = m_custom_light_icons[CustomImage].RootFile; else root[\"result\"][ii][\"Image\"] = \"Light\"; uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]); root[\"result\"][ii][\"UsedByCamera\"] = (camIDX != 0) ? true : false; if (camIDX != 0) { std::stringstream scidx; scidx << camIDX; root[\"result\"][ii][\"CameraIdx\"] = scidx.str(); } root[\"result\"][ii][\"Level\"] = 0; root[\"result\"][ii][\"LevelInt\"] = atoi(sValue.c_str()); } break; case sTypeRego6XXCounter: { time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, <ime); char szDate[40]; sprintf(szDate, \"%04d-%02d-%02d\", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector > result2; strcpy(szTmp, \"0\"); result2 = m_sql.safe_query(\"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')\", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector sd2 = result2[0]; unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10); unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10); unsigned long long total_real; total_real = total_max - total_min; sprintf(szTmp, \"%llu\", total_real); } root[\"result\"][ii][\"SwitchTypeVal\"] = MTYPE_COUNTER; root[\"result\"][ii][\"Counter\"] = sValue; root[\"result\"][ii][\"CounterToday\"] = szTmp; root[\"result\"][ii][\"Data\"] = sValue; root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } break; } } #ifdef ENABLE_PYTHON if (pHardware != NULL) { if (pHardware->HwdType == HTYPE_PythonPlugin) { Plugins::CPlugin *pPlugin = (Plugins::CPlugin*)pHardware; bHaveTimeout = pPlugin->HasNodeFailed(atoi(sd[2].c_str())); root[\"result\"][ii][\"HaveTimeout\"] = bHaveTimeout; } } #endif root[\"result\"][ii][\"Timers\"] = (bHasTimers == true) ? \"true\" : \"false\"; ii++; } } }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":2769,"input":"unicode_unfold_key(OnigCodePoint code) { static const struct ByUnfoldKey wordlist[] = { {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x1040a, 3267, 1}, {0x1e0a, 1727, 1}, {0x040a, 1016, 1}, {0x010a, 186, 1}, {0x1f0a, 2088, 1}, {0x2c0a, 2451, 1}, {0x0189, 619, 1}, {0x1f89, 134, 2}, {0x1f85, 154, 2}, {0x0389, 733, 1}, {0x03ff, 724, 1}, {0xab89, 1523, 1}, {0xab85, 1511, 1}, {0x10c89, 3384, 1}, {0x10c85, 3372, 1}, {0x1e84, 1911, 1}, {0x03f5, 752, 1}, {0x0184, 360, 1}, {0x1f84, 149, 2}, {0x2c84, 2592, 1}, {0x017d, 351, 1}, {0x1ff3, 96, 2}, {0xab84, 1508, 1}, {0xa784, 3105, 1}, {0x10c84, 3369, 1}, {0xab7d, 1487, 1}, {0xa77d, 1706, 1}, {0x1e98, 38, 2}, {0x0498, 1106, 1}, {0x0198, 375, 1}, {0x1f98, 169, 2}, {0x2c98, 2622, 1}, {0x0398, 762, 1}, {0xa684, 2940, 1}, {0xab98, 1568, 1}, {0xa798, 3123, 1}, {0x10c98, 3429, 1}, {0x050a, 1277, 1}, {0x1ffb, 2265, 1}, {0x1e96, 16, 2}, {0x0496, 1103, 1}, {0x0196, 652, 1}, {0x1f96, 199, 2}, {0x2c96, 2619, 1}, {0x0396, 756, 1}, {0xa698, 2970, 1}, {0xab96, 1562, 1}, {0xa796, 3120, 1}, {0x10c96, 3423, 1}, {0x1feb, 2259, 1}, {0x2ceb, 2736, 1}, {0x1e90, 1929, 1}, {0x0490, 1094, 1}, {0x0190, 628, 1}, {0x1f90, 169, 2}, {0x2c90, 2610, 1}, {0x0390, 25, 3}, {0xa696, 2967, 1}, {0xab90, 1544, 1}, {0xa790, 3114, 1}, {0x10c90, 3405, 1}, {0x01d7, 444, 1}, {0x1fd7, 31, 3}, {0x1ea6, 1947, 1}, {0x04a6, 1127, 1}, {0x01a6, 676, 1}, {0x1fa6, 239, 2}, {0x2ca6, 2643, 1}, {0x03a6, 810, 1}, {0xa690, 2958, 1}, {0xaba6, 1610, 1}, {0xa7a6, 3144, 1}, {0x10ca6, 3471, 1}, {0x1ea4, 1944, 1}, {0x04a4, 1124, 1}, {0x01a4, 390, 1}, {0x1fa4, 229, 2}, {0x2ca4, 2640, 1}, {0x03a4, 804, 1}, {0x10a6, 2763, 1}, {0xaba4, 1604, 1}, {0xa7a4, 3141, 1}, {0x10ca4, 3465, 1}, {0x1ea0, 1938, 1}, {0x04a0, 1118, 1}, {0x01a0, 384, 1}, {0x1fa0, 209, 2}, {0x2ca0, 2634, 1}, {0x03a0, 792, 1}, {0x10a4, 2757, 1}, {0xaba0, 1592, 1}, {0xa7a0, 3135, 1}, {0x10ca0, 3453, 1}, {0x1eb2, 1965, 1}, {0x04b2, 1145, 1}, {0x01b2, 694, 1}, {0x1fb2, 249, 2}, {0x2cb2, 2661, 1}, {0x03fd, 718, 1}, {0x10a0, 2745, 1}, {0xabb2, 1646, 1}, {0xa7b2, 703, 1}, {0x10cb2, 3507, 1}, {0x1eac, 1956, 1}, {0x04ac, 1136, 1}, {0x01ac, 396, 1}, {0x1fac, 229, 2}, {0x2cac, 2652, 1}, {0x0537, 1352, 1}, {0x10b2, 2799, 1}, {0xabac, 1628, 1}, {0xa7ac, 637, 1}, {0x10cac, 3489, 1}, {0x1eaa, 1953, 1}, {0x04aa, 1133, 1}, {0x00dd, 162, 1}, {0x1faa, 219, 2}, {0x2caa, 2649, 1}, {0x03aa, 824, 1}, {0x10ac, 2781, 1}, {0xabaa, 1622, 1}, {0xa7aa, 646, 1}, {0x10caa, 3483, 1}, {0x1ea8, 1950, 1}, {0x04a8, 1130, 1}, {0x020a, 517, 1}, {0x1fa8, 209, 2}, {0x2ca8, 2646, 1}, {0x03a8, 817, 1}, {0x10aa, 2775, 1}, {0xaba8, 1616, 1}, {0xa7a8, 3147, 1}, {0x10ca8, 3477, 1}, {0x1ea2, 1941, 1}, {0x04a2, 1121, 1}, {0x01a2, 387, 1}, {0x1fa2, 219, 2}, {0x2ca2, 2637, 1}, {0x118a6, 3528, 1}, {0x10a8, 2769, 1}, {0xaba2, 1598, 1}, {0xa7a2, 3138, 1}, {0x10ca2, 3459, 1}, {0x2ced, 2739, 1}, {0x1fe9, 2283, 1}, {0x1fe7, 47, 3}, {0x1eb0, 1962, 1}, {0x04b0, 1142, 1}, {0x118a4, 3522, 1}, {0x10a2, 2751, 1}, {0x2cb0, 2658, 1}, {0x03b0, 41, 3}, {0x1fe3, 41, 3}, {0xabb0, 1640, 1}, {0xa7b0, 706, 1}, {0x10cb0, 3501, 1}, {0x01d9, 447, 1}, {0x1fd9, 2277, 1}, {0x118a0, 3510, 1}, {0x00df, 24, 2}, {0x00d9, 150, 1}, {0xab77, 1469, 1}, {0x10b0, 2793, 1}, {0x1eae, 1959, 1}, {0x04ae, 1139, 1}, {0x01ae, 685, 1}, {0x1fae, 239, 2}, {0x2cae, 2655, 1}, {0x118b2, 3564, 1}, {0xab73, 1457, 1}, {0xabae, 1634, 1}, {0xab71, 1451, 1}, {0x10cae, 3495, 1}, {0x1e2a, 1775, 1}, {0x042a, 968, 1}, {0x012a, 234, 1}, {0x1f2a, 2130, 1}, {0x2c2a, 2547, 1}, {0x118ac, 3546, 1}, {0x10ae, 2787, 1}, {0x0535, 1346, 1}, {0xa72a, 2988, 1}, {0x1e9a, 0, 2}, {0x049a, 1109, 1}, {0xff37, 3225, 1}, {0x1f9a, 179, 2}, {0x2c9a, 2625, 1}, {0x039a, 772, 1}, {0x118aa, 3540, 1}, {0xab9a, 1574, 1}, {0xa79a, 3126, 1}, {0x10c9a, 3435, 1}, {0x1e94, 1935, 1}, {0x0494, 1100, 1}, {0x0194, 640, 1}, {0x1f94, 189, 2}, {0x2c94, 2616, 1}, {0x0394, 749, 1}, {0x118a8, 3534, 1}, {0xab94, 1556, 1}, {0xa69a, 2973, 1}, {0x10c94, 3417, 1}, {0x10402, 3243, 1}, {0x1e02, 1715, 1}, {0x0402, 992, 1}, {0x0102, 174, 1}, {0x0533, 1340, 1}, {0x2c02, 2427, 1}, {0x118a2, 3516, 1}, {0x052a, 1325, 1}, {0xa694, 2964, 1}, {0x1e92, 1932, 1}, {0x0492, 1097, 1}, {0x2165, 2307, 1}, {0x1f92, 179, 2}, {0x2c92, 2613, 1}, {0x0392, 742, 1}, {0x2161, 2295, 1}, {0xab92, 1550, 1}, {0xa792, 3117, 1}, {0x10c92, 3411, 1}, {0x118b0, 3558, 1}, {0x1f5f, 2199, 1}, {0x1e8e, 1926, 1}, {0x048e, 1091, 1}, {0x018e, 453, 1}, {0x1f8e, 159, 2}, {0x2c8e, 2607, 1}, {0x038e, 833, 1}, {0xa692, 2961, 1}, {0xab8e, 1538, 1}, {0x0055, 59, 1}, {0x10c8e, 3399, 1}, {0x1f5d, 2196, 1}, {0x212a, 27, 1}, {0x04cb, 1181, 1}, {0x01cb, 425, 1}, {0x1fcb, 2241, 1}, {0x118ae, 3552, 1}, {0x0502, 1265, 1}, {0x00cb, 111, 1}, {0xa68e, 2955, 1}, {0x1e8a, 1920, 1}, {0x048a, 1085, 1}, {0x018a, 622, 1}, {0x1f8a, 139, 2}, {0x2c8a, 2601, 1}, {0x038a, 736, 1}, {0x2c67, 2571, 1}, {0xab8a, 1526, 1}, {0x1e86, 1914, 1}, {0x10c8a, 3387, 1}, {0x0186, 616, 1}, {0x1f86, 159, 2}, {0x2c86, 2595, 1}, {0x0386, 727, 1}, {0xff35, 3219, 1}, {0xab86, 1514, 1}, {0xa786, 3108, 1}, {0x10c86, 3375, 1}, {0xa68a, 2949, 1}, {0x0555, 1442, 1}, {0x1ebc, 1980, 1}, {0x04bc, 1160, 1}, {0x01bc, 411, 1}, {0x1fbc, 62, 2}, {0x2cbc, 2676, 1}, {0x1f5b, 2193, 1}, {0xa686, 2943, 1}, {0xabbc, 1676, 1}, {0x1eb8, 1974, 1}, {0x04b8, 1154, 1}, {0x01b8, 408, 1}, {0x1fb8, 2268, 1}, {0x2cb8, 2670, 1}, {0x01db, 450, 1}, {0x1fdb, 2247, 1}, {0xabb8, 1664, 1}, {0x10bc, 2829, 1}, {0x00db, 156, 1}, {0x1eb6, 1971, 1}, {0x04b6, 1151, 1}, {0xff33, 3213, 1}, {0x1fb6, 58, 2}, {0x2cb6, 2667, 1}, {0xff2a, 3186, 1}, {0x10b8, 2817, 1}, {0xabb6, 1658, 1}, {0xa7b6, 3153, 1}, {0x10426, 3351, 1}, {0x1e26, 1769, 1}, {0x0426, 956, 1}, {0x0126, 228, 1}, {0x0053, 52, 1}, {0x2c26, 2535, 1}, {0x0057, 65, 1}, {0x10b6, 2811, 1}, {0x022a, 562, 1}, {0xa726, 2982, 1}, {0x1e2e, 1781, 1}, {0x042e, 980, 1}, {0x012e, 240, 1}, {0x1f2e, 2142, 1}, {0x2c2e, 2559, 1}, {0xffffffff, -1, 0}, {0x2167, 2313, 1}, {0xffffffff, -1, 0}, {0xa72e, 2994, 1}, {0x1e2c, 1778, 1}, {0x042c, 974, 1}, {0x012c, 237, 1}, {0x1f2c, 2136, 1}, {0x2c2c, 2553, 1}, {0x1f6f, 2223, 1}, {0x2c6f, 604, 1}, {0xabbf, 1685, 1}, {0xa72c, 2991, 1}, {0x1e28, 1772, 1}, {0x0428, 962, 1}, {0x0128, 231, 1}, {0x1f28, 2124, 1}, {0x2c28, 2541, 1}, {0xffffffff, -1, 0}, {0x0553, 1436, 1}, {0x10bf, 2838, 1}, {0xa728, 2985, 1}, {0x0526, 1319, 1}, {0x0202, 505, 1}, {0x1e40, 1808, 1}, {0x10424, 3345, 1}, {0x1e24, 1766, 1}, {0x0424, 950, 1}, {0x0124, 225, 1}, {0xffffffff, -1, 0}, {0x2c24, 2529, 1}, {0x052e, 1331, 1}, {0xa740, 3018, 1}, {0x118bc, 3594, 1}, {0xa724, 2979, 1}, {0x1ef2, 2061, 1}, {0x04f2, 1241, 1}, {0x01f2, 483, 1}, {0x1ff2, 257, 2}, {0x2cf2, 2742, 1}, {0x052c, 1328, 1}, {0x118b8, 3582, 1}, {0xa640, 2865, 1}, {0x10422, 3339, 1}, {0x1e22, 1763, 1}, {0x0422, 944, 1}, {0x0122, 222, 1}, {0x2126, 820, 1}, {0x2c22, 2523, 1}, {0x0528, 1322, 1}, {0x01f1, 483, 1}, {0x118b6, 3576, 1}, {0xa722, 2976, 1}, {0x03f1, 796, 1}, {0x1ebe, 1983, 1}, {0x04be, 1163, 1}, {0xfb02, 12, 2}, {0x1fbe, 767, 1}, {0x2cbe, 2679, 1}, {0x01b5, 405, 1}, {0x0540, 1379, 1}, {0xabbe, 1682, 1}, {0x0524, 1316, 1}, {0x00b5, 779, 1}, {0xabb5, 1655, 1}, {0x1eba, 1977, 1}, {0x04ba, 1157, 1}, {0x216f, 2337, 1}, {0x1fba, 2226, 1}, {0x2cba, 2673, 1}, {0x10be, 2835, 1}, {0x0051, 46, 1}, {0xabba, 1670, 1}, {0x10b5, 2808, 1}, {0x1e6e, 1878, 1}, {0x046e, 1055, 1}, {0x016e, 330, 1}, {0x1f6e, 2220, 1}, {0x2c6e, 664, 1}, {0x118bf, 3603, 1}, {0x0522, 1313, 1}, {0x10ba, 2823, 1}, {0xa76e, 3087, 1}, {0x1eb4, 1968, 1}, {0x04b4, 1148, 1}, {0x2c75, 2583, 1}, {0x1fb4, 50, 2}, {0x2cb4, 2664, 1}, {0xab75, 1463, 1}, {0x1ec2, 1989, 1}, {0xabb4, 1652, 1}, {0xa7b4, 3150, 1}, {0x1fc2, 253, 2}, {0x2cc2, 2685, 1}, {0x03c2, 800, 1}, {0x00c2, 83, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff26, 3174, 1}, {0x10b4, 2805, 1}, {0x1eca, 2001, 1}, {0x0551, 1430, 1}, {0x01ca, 425, 1}, {0x1fca, 2238, 1}, {0x2cca, 2697, 1}, {0x10c2, 2847, 1}, {0x00ca, 108, 1}, {0xff2e, 3198, 1}, {0x1e8c, 1923, 1}, {0x048c, 1088, 1}, {0x0226, 556, 1}, {0x1f8c, 149, 2}, {0x2c8c, 2604, 1}, {0x038c, 830, 1}, {0xffffffff, -1, 0}, {0xab8c, 1532, 1}, {0xff2c, 3192, 1}, {0x10c8c, 3393, 1}, {0x1ec4, 1992, 1}, {0x022e, 568, 1}, {0x01c4, 417, 1}, {0x1fc4, 54, 2}, {0x2cc4, 2688, 1}, {0xffffffff, -1, 0}, {0x00c4, 89, 1}, {0xff28, 3180, 1}, {0xa68c, 2952, 1}, {0x01cf, 432, 1}, {0x022c, 565, 1}, {0x118be, 3600, 1}, {0x03cf, 839, 1}, {0x00cf, 123, 1}, {0x118b5, 3573, 1}, {0xffffffff, -1, 0}, {0x10c4, 2853, 1}, {0x216e, 2334, 1}, {0x24cb, 2406, 1}, {0x0228, 559, 1}, {0xff24, 3168, 1}, {0xffffffff, -1, 0}, {0x118ba, 3588, 1}, {0x1efe, 2079, 1}, {0x04fe, 1259, 1}, {0x01fe, 499, 1}, {0x1e9e, 24, 2}, {0x049e, 1115, 1}, {0x03fe, 721, 1}, {0x1f9e, 199, 2}, {0x2c9e, 2631, 1}, {0x039e, 786, 1}, {0x0224, 553, 1}, {0xab9e, 1586, 1}, {0xa79e, 3132, 1}, {0x10c9e, 3447, 1}, {0x01f7, 414, 1}, {0x1ff7, 67, 3}, {0xff22, 3162, 1}, {0x03f7, 884, 1}, {0x118b4, 3570, 1}, {0x049c, 1112, 1}, {0x019c, 661, 1}, {0x1f9c, 189, 2}, {0x2c9c, 2628, 1}, {0x039c, 779, 1}, {0x24bc, 2361, 1}, {0xab9c, 1580, 1}, {0xa79c, 3129, 1}, {0x10c9c, 3441, 1}, {0x0222, 550, 1}, {0x1e7c, 1899, 1}, {0x047c, 1076, 1}, {0x1e82, 1908, 1}, {0x24b8, 2349, 1}, {0x0182, 357, 1}, {0x1f82, 139, 2}, {0x2c82, 2589, 1}, {0xab7c, 1484, 1}, {0xffffffff, -1, 0}, {0xab82, 1502, 1}, {0xa782, 3102, 1}, {0x10c82, 3363, 1}, {0x2c63, 1709, 1}, {0x24b6, 2343, 1}, {0x1e80, 1905, 1}, {0x0480, 1082, 1}, {0x1f59, 2190, 1}, {0x1f80, 129, 2}, {0x2c80, 2586, 1}, {0x0059, 71, 1}, {0xa682, 2937, 1}, {0xab80, 1496, 1}, {0xa780, 3099, 1}, {0x10c80, 3357, 1}, {0xffffffff, -1, 0}, {0x1e4c, 1826, 1}, {0x0145, 270, 1}, {0x014c, 279, 1}, {0x1f4c, 2184, 1}, {0x0345, 767, 1}, {0x0045, 12, 1}, {0x004c, 31, 1}, {0xa680, 2934, 1}, {0xa74c, 3036, 1}, {0x1e4a, 1823, 1}, {0x01d5, 441, 1}, {0x014a, 276, 1}, {0x1f4a, 2178, 1}, {0x03d5, 810, 1}, {0x00d5, 141, 1}, {0x004a, 24, 1}, {0x24bf, 2370, 1}, {0xa74a, 3033, 1}, {0xa64c, 2883, 1}, {0x1041c, 3321, 1}, {0x1e1c, 1754, 1}, {0x041c, 926, 1}, {0x011c, 213, 1}, {0x1f1c, 2118, 1}, {0x2c1c, 2505, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xa64a, 2880, 1}, {0x1041a, 3315, 1}, {0x1e1a, 1751, 1}, {0x041a, 920, 1}, {0x011a, 210, 1}, {0x1f1a, 2112, 1}, {0x2c1a, 2499, 1}, {0xabbd, 1679, 1}, {0x0545, 1394, 1}, {0x054c, 1415, 1}, {0x10418, 3309, 1}, {0x1e18, 1748, 1}, {0x0418, 914, 1}, {0x0118, 207, 1}, {0x1f18, 2106, 1}, {0x2c18, 2493, 1}, {0x10bd, 2832, 1}, {0x2163, 2301, 1}, {0x054a, 1409, 1}, {0x1040e, 3279, 1}, {0x1e0e, 1733, 1}, {0x040e, 1028, 1}, {0x010e, 192, 1}, {0x1f0e, 2100, 1}, {0x2c0e, 2463, 1}, {0x1efc, 2076, 1}, {0x04fc, 1256, 1}, {0x01fc, 496, 1}, {0x1ffc, 96, 2}, {0x051c, 1304, 1}, {0x1040c, 3273, 1}, {0x1e0c, 1730, 1}, {0x040c, 1022, 1}, {0x010c, 189, 1}, {0x1f0c, 2094, 1}, {0x2c0c, 2457, 1}, {0x1f6d, 2217, 1}, {0x2c6d, 607, 1}, {0x051a, 1301, 1}, {0x24be, 2367, 1}, {0x10408, 3261, 1}, {0x1e08, 1724, 1}, {0x0408, 1010, 1}, {0x0108, 183, 1}, {0x1f08, 2082, 1}, {0x2c08, 2445, 1}, {0x04c9, 1178, 1}, {0x0518, 1298, 1}, {0x1fc9, 2235, 1}, {0xffffffff, -1, 0}, {0x24ba, 2355, 1}, {0x00c9, 105, 1}, {0x10416, 3303, 1}, {0x1e16, 1745, 1}, {0x0416, 908, 1}, {0x0116, 204, 1}, {0x050e, 1283, 1}, {0x2c16, 2487, 1}, {0x10414, 3297, 1}, {0x1e14, 1742, 1}, {0x0414, 902, 1}, {0x0114, 201, 1}, {0x042b, 971, 1}, {0x2c14, 2481, 1}, {0x1f2b, 2133, 1}, {0x2c2b, 2550, 1}, {0xffffffff, -1, 0}, {0x050c, 1280, 1}, {0x10406, 3255, 1}, {0x1e06, 1721, 1}, {0x0406, 1004, 1}, {0x0106, 180, 1}, {0x13fb, 1697, 1}, {0x2c06, 2439, 1}, {0x24c2, 2379, 1}, {0x118bd, 3597, 1}, {0xffffffff, -1, 0}, {0x0508, 1274, 1}, {0x10404, 3249, 1}, {0x1e04, 1718, 1}, {0x0404, 998, 1}, {0x0104, 177, 1}, {0x1f95, 194, 2}, {0x2c04, 2433, 1}, {0x0395, 752, 1}, {0x24ca, 2403, 1}, {0xab95, 1559, 1}, {0x0531, 1334, 1}, {0x10c95, 3420, 1}, {0x0516, 1295, 1}, {0x1e6c, 1875, 1}, {0x046c, 1052, 1}, {0x016c, 327, 1}, {0x1f6c, 2214, 1}, {0x216d, 2331, 1}, {0x0514, 1292, 1}, {0x0245, 697, 1}, {0x024c, 598, 1}, {0xa76c, 3084, 1}, {0x10400, 3237, 1}, {0x1e00, 1712, 1}, {0x0400, 986, 1}, {0x0100, 171, 1}, {0x24c4, 2385, 1}, {0x2c00, 2421, 1}, {0x0506, 1271, 1}, {0x024a, 595, 1}, {0x1fab, 224, 2}, {0xa66c, 2931, 1}, {0x03ab, 827, 1}, {0x24cf, 2418, 1}, {0xabab, 1625, 1}, {0xa7ab, 631, 1}, {0x10cab, 3486, 1}, {0xffffffff, -1, 0}, {0x0504, 1268, 1}, {0xffffffff, -1, 0}, {0x021c, 544, 1}, {0x01a9, 679, 1}, {0x1fa9, 214, 2}, {0x10ab, 2778, 1}, {0x03a9, 820, 1}, {0x212b, 92, 1}, {0xaba9, 1619, 1}, {0x1e88, 1917, 1}, {0x10ca9, 3480, 1}, {0x021a, 541, 1}, {0x1f88, 129, 2}, {0x2c88, 2598, 1}, {0x0388, 730, 1}, {0x13fd, 1703, 1}, {0xab88, 1520, 1}, {0x10a9, 2772, 1}, {0x10c88, 3381, 1}, {0xffffffff, -1, 0}, {0x0218, 538, 1}, {0x0500, 1262, 1}, {0x1f4d, 2187, 1}, {0x01a7, 393, 1}, {0x1fa7, 244, 2}, {0x004d, 34, 1}, {0x03a7, 814, 1}, {0xa688, 2946, 1}, {0xaba7, 1613, 1}, {0x020e, 523, 1}, {0x10ca7, 3474, 1}, {0x1e6a, 1872, 1}, {0x046a, 1049, 1}, {0x016a, 324, 1}, {0x1f6a, 2208, 1}, {0xffffffff, -1, 0}, {0x216c, 2328, 1}, {0x10a7, 2766, 1}, {0x01d1, 435, 1}, {0xa76a, 3081, 1}, {0x020c, 520, 1}, {0x03d1, 762, 1}, {0x00d1, 129, 1}, {0x1e68, 1869, 1}, {0x0468, 1046, 1}, {0x0168, 321, 1}, {0x1f68, 2202, 1}, {0xffffffff, -1, 0}, {0xff31, 3207, 1}, {0xa66a, 2928, 1}, {0x0208, 514, 1}, {0xa768, 3078, 1}, {0x1e64, 1863, 1}, {0x0464, 1040, 1}, {0x0164, 315, 1}, {0x054d, 1418, 1}, {0x2c64, 673, 1}, {0xffffffff, -1, 0}, {0xff2b, 3189, 1}, {0xffffffff, -1, 0}, {0xa764, 3072, 1}, {0xa668, 2925, 1}, {0x0216, 535, 1}, {0xffffffff, -1, 0}, {0x118ab, 3543, 1}, {0x1e62, 1860, 1}, {0x0462, 1037, 1}, {0x0162, 312, 1}, {0x0214, 532, 1}, {0x2c62, 655, 1}, {0xa664, 2919, 1}, {0x1ed2, 2013, 1}, {0x04d2, 1193, 1}, {0xa762, 3069, 1}, {0x1fd2, 20, 3}, {0x2cd2, 2709, 1}, {0x118a9, 3537, 1}, {0x00d2, 132, 1}, {0x0206, 511, 1}, {0x10420, 3333, 1}, {0x1e20, 1760, 1}, {0x0420, 938, 1}, {0x0120, 219, 1}, {0xa662, 2916, 1}, {0x2c20, 2517, 1}, {0x1e60, 1856, 1}, {0x0460, 1034, 1}, {0x0160, 309, 1}, {0x0204, 508, 1}, {0x2c60, 2562, 1}, {0xffffffff, -1, 0}, {0x24bd, 2364, 1}, {0x216a, 2322, 1}, {0xa760, 3066, 1}, {0xffffffff, -1, 0}, {0xfb16, 125, 2}, {0x118a7, 3531, 1}, {0x1efa, 2073, 1}, {0x04fa, 1253, 1}, {0x01fa, 493, 1}, {0x1ffa, 2262, 1}, {0xfb14, 109, 2}, {0x03fa, 887, 1}, {0xa660, 2913, 1}, {0x2168, 2316, 1}, {0x01b7, 700, 1}, {0x1fb7, 10, 3}, {0x1f6b, 2211, 1}, {0x2c6b, 2577, 1}, {0x0200, 502, 1}, {0xabb7, 1661, 1}, {0xfb06, 29, 2}, {0x1e56, 1841, 1}, {0x2164, 2304, 1}, {0x0156, 294, 1}, {0x1f56, 62, 3}, {0x0520, 1310, 1}, {0x004f, 40, 1}, {0x0056, 62, 1}, {0x10b7, 2814, 1}, {0xa756, 3051, 1}, {0xfb04, 5, 3}, {0x1e78, 1893, 1}, {0x0478, 1070, 1}, {0x0178, 168, 1}, {0x1e54, 1838, 1}, {0x2162, 2298, 1}, {0x0154, 291, 1}, {0x1f54, 57, 3}, {0xab78, 1472, 1}, {0xa656, 2898, 1}, {0x0054, 56, 1}, {0x1e52, 1835, 1}, {0xa754, 3048, 1}, {0x0152, 288, 1}, {0x1f52, 52, 3}, {0x24c9, 2400, 1}, {0x1e32, 1787, 1}, {0x0052, 49, 1}, {0x0132, 243, 1}, {0xa752, 3045, 1}, {0xffffffff, -1, 0}, {0xfb00, 4, 2}, {0xa654, 2895, 1}, {0xffffffff, -1, 0}, {0xa732, 2997, 1}, {0x2160, 2292, 1}, {0x054f, 1424, 1}, {0x0556, 1445, 1}, {0x1e50, 1832, 1}, {0xa652, 2892, 1}, {0x0150, 285, 1}, {0x1f50, 84, 2}, {0x017b, 348, 1}, {0x1e4e, 1829, 1}, {0x0050, 43, 1}, {0x014e, 282, 1}, {0xa750, 3042, 1}, {0xab7b, 1481, 1}, {0xa77b, 3093, 1}, {0x004e, 37, 1}, {0x0554, 1439, 1}, {0xa74e, 3039, 1}, {0x1e48, 1820, 1}, {0xffffffff, -1, 0}, {0x216b, 2325, 1}, {0x1f48, 2172, 1}, {0xa650, 2889, 1}, {0x0552, 1433, 1}, {0x0048, 21, 1}, {0xffffffff, -1, 0}, {0xa748, 3030, 1}, {0xa64e, 2886, 1}, {0x0532, 1337, 1}, {0x1041e, 3327, 1}, {0x1e1e, 1757, 1}, {0x041e, 932, 1}, {0x011e, 216, 1}, {0x118b7, 3579, 1}, {0x2c1e, 2511, 1}, {0xffffffff, -1, 0}, {0xa648, 2877, 1}, {0x1ff9, 2253, 1}, {0xffffffff, -1, 0}, {0x03f9, 878, 1}, {0x0550, 1427, 1}, {0x10412, 3291, 1}, {0x1e12, 1739, 1}, {0x0412, 896, 1}, {0x0112, 198, 1}, {0x054e, 1421, 1}, {0x2c12, 2475, 1}, {0x10410, 3285, 1}, {0x1e10, 1736, 1}, {0x0410, 890, 1}, {0x0110, 195, 1}, {0xffffffff, -1, 0}, {0x2c10, 2469, 1}, {0x2132, 2289, 1}, {0x0548, 1403, 1}, {0x1ef8, 2070, 1}, {0x04f8, 1250, 1}, {0x01f8, 490, 1}, {0x1ff8, 2250, 1}, {0x0220, 381, 1}, {0x1ee2, 2037, 1}, {0x04e2, 1217, 1}, {0x01e2, 462, 1}, {0x1fe2, 36, 3}, {0x2ce2, 2733, 1}, {0x03e2, 857, 1}, {0x051e, 1307, 1}, {0x1ede, 2031, 1}, {0x04de, 1211, 1}, {0x01de, 456, 1}, {0xffffffff, -1, 0}, {0x2cde, 2727, 1}, {0x03de, 851, 1}, {0x00de, 165, 1}, {0x1f69, 2205, 1}, {0x2c69, 2574, 1}, {0x1eda, 2025, 1}, {0x04da, 1205, 1}, {0x0512, 1289, 1}, {0x1fda, 2244, 1}, {0x2cda, 2721, 1}, {0x03da, 845, 1}, {0x00da, 153, 1}, {0xffffffff, -1, 0}, {0x0510, 1286, 1}, {0x1ed8, 2022, 1}, {0x04d8, 1202, 1}, {0xffffffff, -1, 0}, {0x1fd8, 2274, 1}, {0x2cd8, 2718, 1}, {0x03d8, 842, 1}, {0x00d8, 147, 1}, {0x1ed6, 2019, 1}, {0x04d6, 1199, 1}, {0xffffffff, -1, 0}, {0x1fd6, 76, 2}, {0x2cd6, 2715, 1}, {0x03d6, 792, 1}, {0x00d6, 144, 1}, {0x1ec8, 1998, 1}, {0xffffffff, -1, 0}, {0x01c8, 421, 1}, {0x1fc8, 2232, 1}, {0x2cc8, 2694, 1}, {0xff32, 3210, 1}, {0x00c8, 102, 1}, {0x04c7, 1175, 1}, {0x01c7, 421, 1}, {0x1fc7, 15, 3}, {0x1ec0, 1986, 1}, {0x04c0, 1187, 1}, {0x00c7, 99, 1}, {0xffffffff, -1, 0}, {0x2cc0, 2682, 1}, {0x0179, 345, 1}, {0x00c0, 77, 1}, {0x0232, 574, 1}, {0x01b3, 402, 1}, {0x1fb3, 62, 2}, {0xab79, 1475, 1}, {0xa779, 3090, 1}, {0x10c7, 2859, 1}, {0xabb3, 1649, 1}, {0xa7b3, 3156, 1}, {0x1fa5, 234, 2}, {0x10c0, 2841, 1}, {0x03a5, 807, 1}, {0xffffffff, -1, 0}, {0xaba5, 1607, 1}, {0x01b1, 691, 1}, {0x10ca5, 3468, 1}, {0x10b3, 2802, 1}, {0x2169, 2319, 1}, {0x024e, 601, 1}, {0xabb1, 1643, 1}, {0xa7b1, 682, 1}, {0x10cb1, 3504, 1}, {0x10a5, 2760, 1}, {0xffffffff, -1, 0}, {0x01af, 399, 1}, {0x1faf, 244, 2}, {0xffffffff, -1, 0}, {0x0248, 592, 1}, {0x10b1, 2796, 1}, {0xabaf, 1637, 1}, {0x1fad, 234, 2}, {0x10caf, 3498, 1}, {0x04cd, 1184, 1}, {0x01cd, 429, 1}, {0xabad, 1631, 1}, {0xa7ad, 658, 1}, {0x10cad, 3492, 1}, {0x00cd, 117, 1}, {0x10af, 2790, 1}, {0x021e, 547, 1}, {0x1fa3, 224, 2}, {0xffffffff, -1, 0}, {0x03a3, 800, 1}, {0x10ad, 2784, 1}, {0xaba3, 1601, 1}, {0xffffffff, -1, 0}, {0x10ca3, 3462, 1}, {0x10cd, 2862, 1}, {0x1fa1, 214, 2}, {0x24b7, 2346, 1}, {0x03a1, 796, 1}, {0x0212, 529, 1}, {0xaba1, 1595, 1}, {0x10a3, 2754, 1}, {0x10ca1, 3456, 1}, {0x01d3, 438, 1}, {0x1fd3, 25, 3}, {0x0210, 526, 1}, {0xffffffff, -1, 0}, {0x00d3, 135, 1}, {0x1e97, 34, 2}, {0x10a1, 2748, 1}, {0x0197, 649, 1}, {0x1f97, 204, 2}, {0xffffffff, -1, 0}, {0x0397, 759, 1}, {0x1041d, 3324, 1}, {0xab97, 1565, 1}, {0x041d, 929, 1}, {0x10c97, 3426, 1}, {0x1f1d, 2121, 1}, {0x2c1d, 2508, 1}, {0x1e72, 1884, 1}, {0x0472, 1061, 1}, {0x0172, 336, 1}, {0x118b3, 3567, 1}, {0x2c72, 2580, 1}, {0x0372, 712, 1}, {0x1041b, 3318, 1}, {0xab72, 1454, 1}, {0x041b, 923, 1}, {0x118a5, 3525, 1}, {0x1f1b, 2115, 1}, {0x2c1b, 2502, 1}, {0x1e70, 1881, 1}, {0x0470, 1058, 1}, {0x0170, 333, 1}, {0x118b1, 3561, 1}, {0x2c70, 610, 1}, {0x0370, 709, 1}, {0x1e46, 1817, 1}, {0xab70, 1448, 1}, {0x1e66, 1866, 1}, {0x0466, 1043, 1}, {0x0166, 318, 1}, {0x1e44, 1814, 1}, {0x0046, 15, 1}, {0x118af, 3555, 1}, {0xa746, 3027, 1}, {0xffffffff, -1, 0}, {0xa766, 3075, 1}, {0x0044, 9, 1}, {0x118ad, 3549, 1}, {0xa744, 3024, 1}, {0x1e7a, 1896, 1}, {0x047a, 1073, 1}, {0x1e3a, 1799, 1}, {0xffffffff, -1, 0}, {0xa646, 2874, 1}, {0x1f3a, 2154, 1}, {0xa666, 2922, 1}, {0xab7a, 1478, 1}, {0x118a3, 3519, 1}, {0xa644, 2871, 1}, {0xa73a, 3009, 1}, {0xffffffff, -1, 0}, {0x1ef4, 2064, 1}, {0x04f4, 1244, 1}, {0x01f4, 487, 1}, {0x1ff4, 101, 2}, {0x118a1, 3513, 1}, {0x03f4, 762, 1}, {0x1eec, 2052, 1}, {0x04ec, 1232, 1}, {0x01ec, 477, 1}, {0x1fec, 2286, 1}, {0x0546, 1397, 1}, {0x03ec, 872, 1}, {0xffffffff, -1, 0}, {0x013f, 261, 1}, {0x1f3f, 2169, 1}, {0x0544, 1391, 1}, {0x1eea, 2049, 1}, {0x04ea, 1229, 1}, {0x01ea, 474, 1}, {0x1fea, 2256, 1}, {0xffffffff, -1, 0}, {0x03ea, 869, 1}, {0x1ee8, 2046, 1}, {0x04e8, 1226, 1}, {0x01e8, 471, 1}, {0x1fe8, 2280, 1}, {0x053a, 1361, 1}, {0x03e8, 866, 1}, {0x1ee6, 2043, 1}, {0x04e6, 1223, 1}, {0x01e6, 468, 1}, {0x1fe6, 88, 2}, {0x1f4b, 2181, 1}, {0x03e6, 863, 1}, {0x1e5e, 1853, 1}, {0x004b, 27, 1}, {0x015e, 306, 1}, {0x2166, 2310, 1}, {0x1ee4, 2040, 1}, {0x04e4, 1220, 1}, {0x01e4, 465, 1}, {0x1fe4, 80, 2}, {0xa75e, 3063, 1}, {0x03e4, 860, 1}, {0x1ee0, 2034, 1}, {0x04e0, 1214, 1}, {0x01e0, 459, 1}, {0x053f, 1376, 1}, {0x2ce0, 2730, 1}, {0x03e0, 854, 1}, {0x1edc, 2028, 1}, {0x04dc, 1208, 1}, {0xa65e, 2910, 1}, {0xffffffff, -1, 0}, {0x2cdc, 2724, 1}, {0x03dc, 848, 1}, {0x00dc, 159, 1}, {0x1ed0, 2010, 1}, {0x04d0, 1190, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x2cd0, 2706, 1}, {0x03d0, 742, 1}, {0x00d0, 126, 1}, {0x1ecc, 2004, 1}, {0x054b, 1412, 1}, {0xffffffff, -1, 0}, {0x1fcc, 71, 2}, {0x2ccc, 2700, 1}, {0x1ec6, 1995, 1}, {0x00cc, 114, 1}, {0xffffffff, -1, 0}, {0x1fc6, 67, 2}, {0x2cc6, 2691, 1}, {0x24c8, 2397, 1}, {0x00c6, 96, 1}, {0x04c5, 1172, 1}, {0x01c5, 417, 1}, {0xffffffff, -1, 0}, {0x1fbb, 2229, 1}, {0x24c7, 2394, 1}, {0x00c5, 92, 1}, {0x1fb9, 2271, 1}, {0xabbb, 1673, 1}, {0x24c0, 2373, 1}, {0x04c3, 1169, 1}, {0xabb9, 1667, 1}, {0x1fc3, 71, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x00c3, 86, 1}, {0x10c5, 2856, 1}, {0x10bb, 2826, 1}, {0x1ed4, 2016, 1}, {0x04d4, 1196, 1}, {0x10b9, 2820, 1}, {0x13fc, 1700, 1}, {0x2cd4, 2712, 1}, {0x0246, 589, 1}, {0x00d4, 138, 1}, {0x10c3, 2850, 1}, {0xffffffff, -1, 0}, {0xff3a, 3234, 1}, {0x0244, 688, 1}, {0x019f, 670, 1}, {0x1f9f, 204, 2}, {0xffffffff, -1, 0}, {0x039f, 789, 1}, {0xffffffff, -1, 0}, {0xab9f, 1589, 1}, {0xffffffff, -1, 0}, {0x10c9f, 3450, 1}, {0x019d, 667, 1}, {0x1f9d, 194, 2}, {0x023a, 2565, 1}, {0x039d, 783, 1}, {0x1e5a, 1847, 1}, {0xab9d, 1583, 1}, {0x015a, 300, 1}, {0x10c9d, 3444, 1}, {0x1e9b, 1856, 1}, {0x24cd, 2412, 1}, {0x005a, 74, 1}, {0x1f9b, 184, 2}, {0xa75a, 3057, 1}, {0x039b, 776, 1}, {0x1ece, 2007, 1}, {0xab9b, 1577, 1}, {0x1e99, 42, 2}, {0x10c9b, 3438, 1}, {0x2cce, 2703, 1}, {0x1f99, 174, 2}, {0x00ce, 120, 1}, {0x0399, 767, 1}, {0xa65a, 2904, 1}, {0xab99, 1571, 1}, {0xffffffff, -1, 0}, {0x10c99, 3432, 1}, {0x0193, 634, 1}, {0x1f93, 184, 2}, {0x1e58, 1844, 1}, {0x0393, 746, 1}, {0x0158, 297, 1}, {0xab93, 1553, 1}, {0xffffffff, -1, 0}, {0x10c93, 3414, 1}, {0x0058, 68, 1}, {0x042d, 977, 1}, {0xa758, 3054, 1}, {0x1f2d, 2139, 1}, {0x2c2d, 2556, 1}, {0x118bb, 3591, 1}, {0x0191, 369, 1}, {0x1f91, 174, 2}, {0x118b9, 3585, 1}, {0x0391, 739, 1}, {0xffffffff, -1, 0}, {0xab91, 1547, 1}, {0xa658, 2901, 1}, {0x10c91, 3408, 1}, {0x018f, 625, 1}, {0x1f8f, 164, 2}, {0xffffffff, -1, 0}, {0x038f, 836, 1}, {0xffffffff, -1, 0}, {0xab8f, 1541, 1}, {0xffffffff, -1, 0}, {0x10c8f, 3402, 1}, {0x018b, 366, 1}, {0x1f8b, 144, 2}, {0xffffffff, -1, 0}, {0x0187, 363, 1}, {0x1f87, 164, 2}, {0xab8b, 1529, 1}, {0xa78b, 3111, 1}, {0x10c8b, 3390, 1}, {0xab87, 1517, 1}, {0x04c1, 1166, 1}, {0x10c87, 3378, 1}, {0x1e7e, 1902, 1}, {0x047e, 1079, 1}, {0xffffffff, -1, 0}, {0x00c1, 80, 1}, {0x2c7e, 580, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab7e, 1490, 1}, {0xa77e, 3096, 1}, {0x1e76, 1890, 1}, {0x0476, 1067, 1}, {0x0176, 342, 1}, {0x1e42, 1811, 1}, {0x10c1, 2844, 1}, {0x0376, 715, 1}, {0x1e36, 1793, 1}, {0xab76, 1466, 1}, {0x0136, 249, 1}, {0x0042, 3, 1}, {0x1e3e, 1805, 1}, {0xa742, 3021, 1}, {0x1e38, 1796, 1}, {0x1f3e, 2166, 1}, {0xa736, 3003, 1}, {0x1f38, 2148, 1}, {0xffffffff, -1, 0}, {0x0587, 105, 2}, {0xa73e, 3015, 1}, {0xffffffff, -1, 0}, {0xa738, 3006, 1}, {0xa642, 2868, 1}, {0x1e5c, 1850, 1}, {0x1e34, 1790, 1}, {0x015c, 303, 1}, {0x0134, 246, 1}, {0x1ef6, 2067, 1}, {0x04f6, 1247, 1}, {0x01f6, 372, 1}, {0x1ff6, 92, 2}, {0xa75c, 3060, 1}, {0xa734, 3000, 1}, {0x1ef0, 2058, 1}, {0x04f0, 1238, 1}, {0x01f0, 20, 2}, {0xffffffff, -1, 0}, {0x1e30, 1784, 1}, {0x03f0, 772, 1}, {0x0130, 261, 2}, {0x0542, 1385, 1}, {0xa65c, 2907, 1}, {0x1f83, 144, 2}, {0x0536, 1349, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab83, 1505, 1}, {0x053e, 1373, 1}, {0x10c83, 3366, 1}, {0x0538, 1355, 1}, {0x1eee, 2055, 1}, {0x04ee, 1235, 1}, {0x01ee, 480, 1}, {0x1f8d, 154, 2}, {0xffffffff, -1, 0}, {0x03ee, 875, 1}, {0xffffffff, -1, 0}, {0xab8d, 1535, 1}, {0xa78d, 643, 1}, {0x10c8d, 3396, 1}, {0x0534, 1343, 1}, {0x0181, 613, 1}, {0x1f81, 134, 2}, {0x013d, 258, 1}, {0x1f3d, 2163, 1}, {0xffffffff, -1, 0}, {0xab81, 1499, 1}, {0x017f, 52, 1}, {0x10c81, 3360, 1}, {0x2c7f, 583, 1}, {0x037f, 881, 1}, {0xff2d, 3195, 1}, {0xab7f, 1493, 1}, {0x1e74, 1887, 1}, {0x0474, 1064, 1}, {0x0174, 339, 1}, {0x1e3c, 1802, 1}, {0x0149, 46, 2}, {0x1f49, 2175, 1}, {0x1f3c, 2160, 1}, {0xab74, 1460, 1}, {0x0049, 3606, 1}, {0x0143, 267, 1}, {0x24cc, 2409, 1}, {0xa73c, 3012, 1}, {0xffffffff, -1, 0}, {0x0043, 6, 1}, {0x0141, 264, 1}, {0x24c6, 2391, 1}, {0x013b, 255, 1}, {0x1f3b, 2157, 1}, {0x0041, 0, 1}, {0x0139, 252, 1}, {0x1f39, 2151, 1}, {0x24c5, 2388, 1}, {0x24bb, 2358, 1}, {0x13fa, 1694, 1}, {0x053d, 1370, 1}, {0x24b9, 2352, 1}, {0x0429, 965, 1}, {0x2183, 2340, 1}, {0x1f29, 2127, 1}, {0x2c29, 2544, 1}, {0x24c3, 2382, 1}, {0x10427, 3354, 1}, {0x10425, 3348, 1}, {0x0427, 959, 1}, {0x0425, 953, 1}, {0xffffffff, -1, 0}, {0x2c27, 2538, 1}, {0x2c25, 2532, 1}, {0x0549, 1406, 1}, {0x053c, 1367, 1}, {0x10423, 3342, 1}, {0xffffffff, -1, 0}, {0x0423, 947, 1}, {0x0543, 1388, 1}, {0xffffffff, -1, 0}, {0x2c23, 2526, 1}, {0xff36, 3222, 1}, {0xffffffff, -1, 0}, {0x0541, 1382, 1}, {0x10421, 3336, 1}, {0x053b, 1364, 1}, {0x0421, 941, 1}, {0xff38, 3228, 1}, {0x0539, 1358, 1}, {0x2c21, 2520, 1}, {0x10419, 3312, 1}, {0x10417, 3306, 1}, {0x0419, 917, 1}, {0x0417, 911, 1}, {0x1f19, 2109, 1}, {0x2c19, 2496, 1}, {0x2c17, 2490, 1}, {0x023e, 2568, 1}, {0xff34, 3216, 1}, {0x10415, 3300, 1}, {0x10413, 3294, 1}, {0x0415, 905, 1}, {0x0413, 899, 1}, {0xffffffff, -1, 0}, {0x2c15, 2484, 1}, {0x2c13, 2478, 1}, {0xffffffff, -1, 0}, {0x24ce, 2415, 1}, {0x1040f, 3282, 1}, {0xffffffff, -1, 0}, {0x040f, 1031, 1}, {0xff30, 3204, 1}, {0x1f0f, 2103, 1}, {0x2c0f, 2466, 1}, {0x1040d, 3276, 1}, {0xffffffff, -1, 0}, {0x040d, 1025, 1}, {0x0147, 273, 1}, {0x1f0d, 2097, 1}, {0x2c0d, 2460, 1}, {0x1040b, 3270, 1}, {0x0047, 18, 1}, {0x040b, 1019, 1}, {0x0230, 571, 1}, {0x1f0b, 2091, 1}, {0x2c0b, 2454, 1}, {0x10409, 3264, 1}, {0x10405, 3252, 1}, {0x0409, 1013, 1}, {0x0405, 1001, 1}, {0x1f09, 2085, 1}, {0x2c09, 2448, 1}, {0x2c05, 2436, 1}, {0x10403, 3246, 1}, {0x10401, 3240, 1}, {0x0403, 995, 1}, {0x0401, 989, 1}, {0xffffffff, -1, 0}, {0x2c03, 2430, 1}, {0x2c01, 2424, 1}, {0x13f9, 1691, 1}, {0x042f, 983, 1}, {0xffffffff, -1, 0}, {0x1f2f, 2145, 1}, {0x1041f, 3330, 1}, {0xffffffff, -1, 0}, {0x041f, 935, 1}, {0x023d, 378, 1}, {0x10411, 3288, 1}, {0x2c1f, 2514, 1}, {0x0411, 893, 1}, {0x0547, 1400, 1}, {0xffffffff, -1, 0}, {0x2c11, 2472, 1}, {0x10407, 3258, 1}, {0xffffffff, -1, 0}, {0x0407, 1007, 1}, {0x24c1, 2376, 1}, {0xffffffff, -1, 0}, {0x2c07, 2442, 1}, {0xffffffff, -1, 0}, {0x13f8, 1688, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff39, 3231, 1}, {0xffffffff, -1, 0}, {0x0243, 354, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x0241, 586, 1}, {0xff29, 3183, 1}, {0x023b, 577, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff27, 3177, 1}, {0xff25, 3171, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff23, 3165, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff21, 3159, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb17, 117, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff2f, 3201, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb15, 113, 2}, {0xfb13, 121, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb05, 29, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb03, 0, 3}, {0xfb01, 8, 2} }; if (0 == 0) { int key = hash(&code); if (key <= MAX_HASH_VALUE && key >= 0) { OnigCodePoint gcode = wordlist[key].code; if (code == gcode) return &wordlist[key]; } } return 0; }","output":{"is_vulnerable":"True","vulnerability_types":["Out-of-bounds Write"],"explanation":"An issue was discovered in Oniguruma 6.2.0, as used in Oniguruma-mod in Ruby through 2.4.1 and mbstring in PHP through 7.1.5. A stack out-of-bounds write in onigenc_unicode_get_case_fold_codes_by_str() occurs during regular expression compilation. Code point 0xFFFFFFFF is not properly handled in unicode_unfold_key(). A malformed regular expression could result in 4 bytes being written off the end of a stack buffer of expand_case_fold_string() during the call to onigenc_unicode_get_case_fold_codes_by_str(), a typical stack buffer overflow.","severity_level":"High","cwe":"CWE-787","cve":"CVE-2017-9225"}} -{"idx":478410,"input":"WandExport MagickBooleanType MogrifyImageCommand(ImageInfo *image_info, int argc,char **argv,char **wand_unused(metadata),ExceptionInfo *exception) { #define DestroyMogrify() \\ { \\ if (format != (char *) NULL) \\ format=DestroyString(format); \\ if (path != (char *) NULL) \\ path=DestroyString(path); \\ DestroyImageStack(); \\ for (i=0; i < (ssize_t) argc; i++) \\ argv[i]=DestroyString(argv[i]); \\ argv=(char **) RelinquishMagickMemory(argv); \\ } #define ThrowMogrifyException(asperity,tag,option) \\ { \\ (void) ThrowMagickException(exception,GetMagickModule(),asperity,tag,\"`%s'\", \\ option); \\ DestroyMogrify(); \\ return(MagickFalse); \\ } #define ThrowMogrifyInvalidArgumentException(option,argument) \\ { \\ (void) ThrowMagickException(exception,GetMagickModule(),OptionError, \\ \"InvalidArgument\",\"'%s': %s\",argument,option); \\ DestroyMogrify(); \\ return(MagickFalse); \\ } char *format, *option, *path; Image *image; ImageStack image_stack[MaxImageStackDepth+1]; MagickBooleanType global_colormap; MagickBooleanType fire, pend, respect_parenthesis; MagickStatusType status; register ssize_t i; ssize_t j, k; wand_unreferenced(metadata); \/* Set defaults. *\/ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\"); assert(exception != (ExceptionInfo *) NULL); if (argc == 2) { option=argv[1]; if ((LocaleCompare(\"version\",option+1) == 0) || (LocaleCompare(\"-version\",option+1) == 0)) { ListMagickVersion(stdout); return(MagickTrue); } } if (argc < 2) return(MogrifyUsage()); format=(char *) NULL; path=(char *) NULL; global_colormap=MagickFalse; k=0; j=1; NewImageStack(); option=(char *) NULL; pend=MagickFalse; respect_parenthesis=MagickFalse; status=MagickTrue; \/* Parse command line. *\/ ReadCommandlLine(argc,&argv); status=ExpandFilenames(&argc,&argv); if (status == MagickFalse) ThrowMogrifyException(ResourceLimitError,\"MemoryAllocationFailed\", GetExceptionMessage(errno)); for (i=1; i < (ssize_t) argc; i++) { option=argv[i]; if (LocaleCompare(option,\"(\") == 0) { FireImageStack(MagickFalse,MagickTrue,pend); if (k == MaxImageStackDepth) ThrowMogrifyException(OptionError,\"ParenthesisNestedTooDeeply\", option); PushImageStack(); continue; } if (LocaleCompare(option,\")\") == 0) { FireImageStack(MagickFalse,MagickTrue,MagickTrue); if (k == 0) ThrowMogrifyException(OptionError,\"UnableToParseExpression\",option); PopImageStack(); continue; } if (IsCommandOption(option) == MagickFalse) { char backup_filename[MagickPathExtent], *filename; Image *images; struct stat properties; \/* Option is a file name: begin by reading image from specified file. *\/ FireImageStack(MagickFalse,MagickFalse,pend); filename=argv[i]; if ((LocaleCompare(filename,\"--\") == 0) && (i < (ssize_t) (argc-1))) filename=argv[++i]; images=ReadImages(image_info,filename,exception); status&=(images != (Image *) NULL) && (exception->severity < ErrorException); if (images == (Image *) NULL) continue; properties=(*GetBlobProperties(images)); if (format != (char *) NULL) (void) CopyMagickString(images->filename,images->magick_filename, MagickPathExtent); if (path != (char *) NULL) { GetPathComponent(option,TailPath,filename); (void) FormatLocaleString(images->filename,MagickPathExtent, \"%s%c%s\",path,*DirectorySeparator,filename); } if (format != (char *) NULL) AppendImageFormat(format,images->filename); AppendImageStack(images); FinalizeImageSettings(image_info,image,MagickFalse); if (global_colormap != MagickFalse) { QuantizeInfo *quantize_info; quantize_info=AcquireQuantizeInfo(image_info); (void) RemapImages(quantize_info,images,(Image *) NULL,exception); quantize_info=DestroyQuantizeInfo(quantize_info); } *backup_filename='\\0'; if ((LocaleCompare(image->filename,\"-\") != 0) && (IsPathWritable(image->filename) != MagickFalse)) { \/* Rename image file as backup. *\/ (void) CopyMagickString(backup_filename,image->filename, MagickPathExtent); for (j=0; j < 6; j++) { (void) ConcatenateMagickString(backup_filename,\"~\", MagickPathExtent); if (IsPathAccessible(backup_filename) == MagickFalse) break; } if ((IsPathAccessible(backup_filename) != MagickFalse) || (rename_utf8(image->filename,backup_filename) != 0)) *backup_filename='\\0'; } \/* Write transmogrified image to disk. *\/ image_info->synchronize=MagickTrue; status&=WriteImages(image_info,image,image->filename,exception); if (status != MagickFalse) { #if defined(MAGICKCORE_HAVE_UTIME) { MagickBooleanType preserve_timestamp; preserve_timestamp=IsStringTrue(GetImageOption(image_info, \"preserve-timestamp\")); if (preserve_timestamp != MagickFalse) { struct utimbuf timestamp; timestamp.actime=properties.st_atime; timestamp.modtime=properties.st_mtime; (void) utime(image->filename,×tamp); } } #endif if (*backup_filename != '\\0') (void) remove_utf8(backup_filename); } RemoveAllImageStack(); continue; } pend=image != (Image *) NULL ? MagickTrue : MagickFalse; switch (*(option+1)) { case 'a': { if (LocaleCompare(\"adaptive-blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"adaptive-resize\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"adaptive-sharpen\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"affine\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"alpha\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickAlphaChannelOptions,MagickFalse, argv[i]); if (type < 0) ThrowMogrifyException(OptionError, \"UnrecognizedAlphaChannelOption\",argv[i]); break; } if (LocaleCompare(\"annotate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); i++; break; } if (LocaleCompare(\"antialias\",option+1) == 0) break; if (LocaleCompare(\"append\",option+1) == 0) break; if (LocaleCompare(\"attenuate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"authenticate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"auto-gamma\",option+1) == 0) break; if (LocaleCompare(\"auto-level\",option+1) == 0) break; if (LocaleCompare(\"auto-orient\",option+1) == 0) break; if (LocaleCompare(\"auto-threshold\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickAutoThresholdOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError,\"UnrecognizedThresholdMethod\", argv[i]); break; } if (LocaleCompare(\"average\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'b': { if (LocaleCompare(\"background\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"bias\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"black-point-compensation\",option+1) == 0) break; if (LocaleCompare(\"black-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"blue-primary\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"blue-shift\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"border\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"bordercolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"box\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"brightness-contrast\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'c': { if (LocaleCompare(\"cache\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"canny\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"caption\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"channel\",option+1) == 0) { ssize_t channel; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); channel=ParseChannelOption(argv[i]); if (channel < 0) ThrowMogrifyException(OptionError,\"UnrecognizedChannelType\", argv[i]); break; } if (LocaleCompare(\"channel-fx\",option+1) == 0) { ssize_t channel; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); channel=ParsePixelChannelOption(argv[i]); if (channel < 0) ThrowMogrifyException(OptionError,\"UnrecognizedChannelType\", argv[i]); break; } if (LocaleCompare(\"cdl\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"charcoal\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"chop\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"clahe\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"clamp\",option+1) == 0) break; if (LocaleCompare(\"clip\",option+1) == 0) break; if (LocaleCompare(\"clip-mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"clut\",option+1) == 0) break; if (LocaleCompare(\"coalesce\",option+1) == 0) break; if (LocaleCompare(\"colorize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"color-matrix\",option+1) == 0) { KernelInfo *kernel_info; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); kernel_info=AcquireKernelInfo(argv[i],exception); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"colors\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"colorspace\",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedColorspace\", argv[i]); break; } if (LocaleCompare(\"combine\",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedColorspace\", argv[i]); break; } if (LocaleCompare(\"compare\",option+1) == 0) break; if (LocaleCompare(\"comment\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"composite\",option+1) == 0) break; if (LocaleCompare(\"compress\",option+1) == 0) { ssize_t compress; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); compress=ParseCommandOption(MagickCompressOptions,MagickFalse, argv[i]); if (compress < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageCompression\", argv[i]); break; } if (LocaleCompare(\"concurrent\",option+1) == 0) break; if (LocaleCompare(\"connected-components\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"contrast\",option+1) == 0) break; if (LocaleCompare(\"contrast-stretch\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"convolve\",option+1) == 0) { KernelInfo *kernel_info; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); kernel_info=AcquireKernelInfo(argv[i],exception); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"copy\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"crop\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"cycle\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'd': { if (LocaleCompare(\"decipher\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"deconstruct\",option+1) == 0) break; if (LocaleCompare(\"debug\",option+1) == 0) { ssize_t event; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); event=ParseCommandOption(MagickLogEventOptions,MagickFalse,argv[i]); if (event < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEventType\", argv[i]); (void) SetLogEventMask(argv[i]); break; } if (LocaleCompare(\"define\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (*option == '+') { const char *define; define=GetImageOption(image_info,argv[i]); if (define == (const char *) NULL) ThrowMogrifyException(OptionError,\"NoSuchOption\",argv[i]); break; } break; } if (LocaleCompare(\"delay\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"delete\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"density\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"depth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"deskew\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"despeckle\",option+1) == 0) break; if (LocaleCompare(\"dft\",option+1) == 0) break; if (LocaleCompare(\"direction\",option+1) == 0) { ssize_t direction; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, argv[i]); if (direction < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDirectionType\", argv[i]); break; } if (LocaleCompare(\"display\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"dispose\",option+1) == 0) { ssize_t dispose; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, argv[i]); if (dispose < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDisposeMethod\", argv[i]); break; } if (LocaleCompare(\"distort\",option+1) == 0) { ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickDistortOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDistortMethod\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"dither\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickDitherOptions,MagickFalse,argv[i]); if (method < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDitherMethod\", argv[i]); break; } if (LocaleCompare(\"draw\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"duplicate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"duration\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'e': { if (LocaleCompare(\"edge\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"emboss\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"encipher\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"encoding\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"endian\",option+1) == 0) { ssize_t endian; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); endian=ParseCommandOption(MagickEndianOptions,MagickFalse,argv[i]); if (endian < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEndianType\", argv[i]); break; } if (LocaleCompare(\"enhance\",option+1) == 0) break; if (LocaleCompare(\"equalize\",option+1) == 0) break; if (LocaleCompare(\"evaluate\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEvaluateOperator\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"evaluate-sequence\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEvaluateOperator\", argv[i]); break; } if (LocaleCompare(\"extent\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"extract\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'f': { if (LocaleCompare(\"family\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"features\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"fill\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"filter\",option+1) == 0) { ssize_t filter; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); filter=ParseCommandOption(MagickFilterOptions,MagickFalse,argv[i]); if (filter < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageFilter\", argv[i]); break; } if (LocaleCompare(\"flatten\",option+1) == 0) break; if (LocaleCompare(\"flip\",option+1) == 0) break; if (LocaleCompare(\"flop\",option+1) == 0) break; if (LocaleCompare(\"floodfill\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"font\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"format\",option+1) == 0) { (void) CopyMagickString(argv[i]+1,\"sans\",MagickPathExtent); (void) CloneString(&format,(char *) NULL); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); (void) CloneString(&format,argv[i]); (void) CopyMagickString(image_info->filename,format, MagickPathExtent); (void) ConcatenateMagickString(image_info->filename,\":\", MagickPathExtent); (void) SetImageInfo(image_info,0,exception); if (*image_info->magick == '\\0') ThrowMogrifyException(OptionError,\"UnrecognizedImageFormat\", format); break; } if (LocaleCompare(\"frame\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"function\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickFunctionOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedFunction\",argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"fuzz\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"fx\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'g': { if (LocaleCompare(\"gamma\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if ((LocaleCompare(\"gaussian-blur\",option+1) == 0) || (LocaleCompare(\"gaussian\",option+1) == 0)) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"geometry\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"gravity\",option+1) == 0) { ssize_t gravity; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse, argv[i]); if (gravity < 0) ThrowMogrifyException(OptionError,\"UnrecognizedGravityType\", argv[i]); break; } if (LocaleCompare(\"grayscale\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickPixelIntensityOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError,\"UnrecognizedIntensityMethod\", argv[i]); break; } if (LocaleCompare(\"green-primary\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'h': { if (LocaleCompare(\"hald-clut\",option+1) == 0) break; if ((LocaleCompare(\"help\",option+1) == 0) || (LocaleCompare(\"-help\",option+1) == 0)) return(MogrifyUsage()); if (LocaleCompare(\"hough-lines\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'i': { if (LocaleCompare(\"identify\",option+1) == 0) break; if (LocaleCompare(\"idft\",option+1) == 0) break; if (LocaleCompare(\"implode\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"intensity\",option+1) == 0) { ssize_t intensity; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,argv[i]); if (intensity < 0) ThrowMogrifyException(OptionError, \"UnrecognizedPixelIntensityMethod\",argv[i]); break; } if (LocaleCompare(\"intent\",option+1) == 0) { ssize_t intent; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); intent=ParseCommandOption(MagickIntentOptions,MagickFalse,argv[i]); if (intent < 0) ThrowMogrifyException(OptionError,\"UnrecognizedIntentType\", argv[i]); break; } if (LocaleCompare(\"interlace\",option+1) == 0) { ssize_t interlace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); interlace=ParseCommandOption(MagickInterlaceOptions,MagickFalse, argv[i]); if (interlace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedInterlaceType\", argv[i]); break; } if (LocaleCompare(\"interline-spacing\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"interpolate\",option+1) == 0) { ssize_t interpolate; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse, argv[i]); if (interpolate < 0) ThrowMogrifyException(OptionError,\"UnrecognizedInterpolateMethod\", argv[i]); break; } if (LocaleCompare(\"interword-spacing\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'k': { if (LocaleCompare(\"kerning\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"kuwahara\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'l': { if (LocaleCompare(\"label\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"lat\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); } if (LocaleCompare(\"layers\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickLayerOptions,MagickFalse,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedLayerMethod\", argv[i]); break; } if (LocaleCompare(\"level\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"level-colors\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"limit\",option+1) == 0) { char *p; double value; ssize_t resource; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); resource=ParseCommandOption(MagickResourceOptions,MagickFalse, argv[i]); if (resource < 0) ThrowMogrifyException(OptionError,\"UnrecognizedResourceType\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); value=StringToDouble(argv[i],&p); (void) value; if ((p == argv[i]) && (LocaleCompare(\"unlimited\",argv[i]) != 0)) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"liquid-rescale\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"list\",option+1) == 0) { ssize_t list; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); list=ParseCommandOption(MagickListOptions,MagickFalse,argv[i]); if (list < 0) ThrowMogrifyException(OptionError,\"UnrecognizedListType\",argv[i]); status=MogrifyImageInfo(image_info,(int) (i-j+1),(const char **) argv+j,exception); return(status == 0 ? MagickFalse : MagickTrue); } if (LocaleCompare(\"log\",option+1) == 0) { if (*option == '+') break; i++; if ((i == (ssize_t) argc) || (strchr(argv[i],'%') == (char *) NULL)) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"loop\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'm': { if (LocaleCompare(\"magnify\",option+1) == 0) break; if (LocaleCompare(\"map\",option+1) == 0) { global_colormap=(*option == '+') ? MagickTrue : MagickFalse; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"matte\",option+1) == 0) break; if (LocaleCompare(\"mattecolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"maximum\",option+1) == 0) break; if (LocaleCompare(\"mean-shift\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"median\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"metric\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickMetricOptions,MagickTrue,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedMetricType\", argv[i]); break; } if (LocaleCompare(\"minimum\",option+1) == 0) break; if (LocaleCompare(\"modulate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"mode\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"monitor\",option+1) == 0) break; if (LocaleCompare(\"monochrome\",option+1) == 0) break; if (LocaleCompare(\"morph\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"morphology\",option+1) == 0) { char token[MagickPathExtent]; KernelInfo *kernel_info; ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); GetNextToken(argv[i],(const char **) NULL,MagickPathExtent,token); op=ParseCommandOption(MagickMorphologyOptions,MagickFalse,token); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedMorphologyMethod\", token); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); kernel_info=AcquireKernelInfo(argv[i],exception); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"mosaic\",option+1) == 0) break; if (LocaleCompare(\"motion-blur\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'n': { if (LocaleCompare(\"negate\",option+1) == 0) break; if (LocaleCompare(\"noise\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (*option == '+') { ssize_t noise; noise=ParseCommandOption(MagickNoiseOptions,MagickFalse, argv[i]); if (noise < 0) ThrowMogrifyException(OptionError,\"UnrecognizedNoiseType\", argv[i]); break; } if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"noop\",option+1) == 0) break; if (LocaleCompare(\"normalize\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'o': { if (LocaleCompare(\"opaque\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"ordered-dither\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"orient\",option+1) == 0) { ssize_t orientation; orientation=UndefinedOrientation; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); orientation=ParseCommandOption(MagickOrientationOptions,MagickFalse, argv[i]); if (orientation < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageOrientation\", argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'p': { if (LocaleCompare(\"page\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"paint\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"path\",option+1) == 0) { (void) CloneString(&path,(char *) NULL); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); (void) CloneString(&path,argv[i]); break; } if (LocaleCompare(\"perceptible\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"pointsize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"polaroid\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"poly\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"posterize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"precision\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"print\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"process\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"profile\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'q': { if (LocaleCompare(\"quality\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"quantize\",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedColorspace\", argv[i]); break; } if (LocaleCompare(\"quiet\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'r': { if (LocaleCompare(\"rotational-blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"raise\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"random-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"range-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"read-mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"red-primary\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); } if (LocaleCompare(\"regard-warnings\",option+1) == 0) break; if (LocaleCompare(\"region\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"remap\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"render\",option+1) == 0) break; if (LocaleCompare(\"repage\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"resample\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"resize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleNCompare(\"respect-parentheses\",option+1,17) == 0) { respect_parenthesis=(*option == '-') ? MagickTrue : MagickFalse; break; } if (LocaleCompare(\"reverse\",option+1) == 0) break; if (LocaleCompare(\"roll\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"rotate\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 's': { if (LocaleCompare(\"sample\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sampling-factor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"scale\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"scene\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"seed\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"segment\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"selective-blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"separate\",option+1) == 0) break; if (LocaleCompare(\"sepia-tone\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"set\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"shade\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"shadow\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sharpen\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"shave\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"shear\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sigmoidal-contrast\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"size\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sketch\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"smush\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; break; } if (LocaleCompare(\"solarize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sparse-color\",option+1) == 0) { ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickSparseColorOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedSparseColorMethod\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"splice\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"spread\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"statistic\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickStatisticOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedStatisticType\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"stretch\",option+1) == 0) { ssize_t stretch; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse, argv[i]); if (stretch < 0) ThrowMogrifyException(OptionError,\"UnrecognizedStyleType\", argv[i]); break; } if (LocaleCompare(\"strip\",option+1) == 0) break; if (LocaleCompare(\"stroke\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"strokewidth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"style\",option+1) == 0) { ssize_t style; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); style=ParseCommandOption(MagickStyleOptions,MagickFalse,argv[i]); if (style < 0) ThrowMogrifyException(OptionError,\"UnrecognizedStyleType\", argv[i]); break; } if (LocaleCompare(\"swap\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"swirl\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"synchronize\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 't': { if (LocaleCompare(\"taint\",option+1) == 0) break; if (LocaleCompare(\"texture\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"tile\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"tile-offset\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"tint\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"transform\",option+1) == 0) break; if (LocaleCompare(\"transpose\",option+1) == 0) break; if (LocaleCompare(\"transverse\",option+1) == 0) break; if (LocaleCompare(\"threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"thumbnail\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"transparent\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"transparent-color\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"treedepth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"trim\",option+1) == 0) break; if (LocaleCompare(\"type\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickTypeOptions,MagickFalse,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageType\", argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'u': { if (LocaleCompare(\"undercolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"unique-colors\",option+1) == 0) break; if (LocaleCompare(\"units\",option+1) == 0) { ssize_t units; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); units=ParseCommandOption(MagickResolutionOptions,MagickFalse, argv[i]); if (units < 0) ThrowMogrifyException(OptionError,\"UnrecognizedUnitsType\", argv[i]); break; } if (LocaleCompare(\"unsharp\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'v': { if (LocaleCompare(\"verbose\",option+1) == 0) { image_info->verbose=(*option == '-') ? MagickTrue : MagickFalse; break; } if ((LocaleCompare(\"version\",option+1) == 0) || (LocaleCompare(\"-version\",option+1) == 0)) { ListMagickVersion(stdout); break; } if (LocaleCompare(\"vignette\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"virtual-pixel\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickVirtualPixelOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError, \"UnrecognizedVirtualPixelMethod\",argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'w': { if (LocaleCompare(\"wave\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"wavelet-denoise\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"weight\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"white-point\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"white-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"write\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"write-mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case '?': break; default: ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } fire=(GetCommandOptionFlags(MagickCommandOptions,MagickFalse,option) & FireOptionFlag) == 0 ? MagickFalse : MagickTrue; if (fire != MagickFalse) FireImageStack(MagickFalse,MagickTrue,MagickTrue); } if (k != 0) ThrowMogrifyException(OptionError,\"UnbalancedParenthesis\",argv[i]); if (i != (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingAnImageFilename\",argv[i]); DestroyMogrify(); return(status != 0 ? MagickTrue : MagickFalse); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":404397,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { char s[2]; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MaxTextExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MaxTextExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; \/* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; *\/ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; property=(const char *) NULL; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->magick= %s\",image_info->magick); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register PixelPacket *r; ExceptionInfo *exception; exception=(&image->exception); if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->matte == MagickFalse))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ number_opaque = (int) image->colors; if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; else ping_have_color=MagickTrue; ping_have_non_bw=MagickFalse; if (image->matte != MagickFalse) { number_transparent = 2; number_semitransparent = 1; } else { number_transparent = 0; number_semitransparent = 0; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->matte is MagickFalse, we ignore the opacity channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ ExceptionInfo *exception; int n; PixelPacket opaque[260], semitransparent[260], transparent[260]; register IndexPacket *indexes; register const PixelPacket *s, *q; register PixelPacket *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->matte=%.20g\",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,opacity)\"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } exception=(&image->exception); image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte == MagickFalse || GetPixelOpacity(q) == OpaqueOpacity) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelRGB(q, opaque); opaque[0].opacity=OpaqueOpacity; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(q, opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelRGB(q, opaque+i); opaque[i].opacity=OpaqueOpacity; } } } else if (q->opacity == TransparentOpacity) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelRGBO(q, transparent); ping_trans_color.red= (unsigned short) GetPixelRed(q); ping_trans_color.green= (unsigned short) GetPixelGreen(q); ping_trans_color.blue= (unsigned short) GetPixelBlue(q); ping_trans_color.gray= (unsigned short) GetPixelRed(q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(q, transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelRGBO(q, transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelRGBO(q, semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(q, semitransparent+i) && GetPixelOpacity(q) == semitransparent[i].opacity) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelRGBO(q, semitransparent+i); } } } q++; } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != GetPixelGreen(s) || GetPixelRed(s) != GetPixelBlue(s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s++; } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != 0 && GetPixelRed(s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s++; } } } } } if (image_colors < 257) { PixelPacket colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->matte == MagickFalse || image->colormap[i].opacity == GetPixelOpacity(q)) && image->colormap[i].red == GetPixelRed(q) && image->colormap[i].green == GetPixelGreen(q) && image->colormap[i].blue == GetPixelBlue(q)) { SetPixelIndex(indexes+x,i); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,opacity)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) > TransparentOpacity\/2) { SetPixelOpacity(r,TransparentOpacity); SetPixelRgb(r,&image->background_color); } else SetPixelOpacity(r,OpaqueOpacity); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].opacity = (image->colormap[i].opacity > TransparentOpacity\/2 ? TransparentOpacity : OpaqueOpacity); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR04PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR03PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR02PixelBlue(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 && GetPixelOpacity(r) == OpaqueOpacity) { SetPixelRed(r,ScaleCharToQuantum(0x24)); } r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { ExceptionInfo *exception; register const PixelPacket *q; exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (q->opacity != TransparentOpacity && (unsigned short) GetPixelRed(q) == ping_trans_color.red && (unsigned short) GetPixelGreen(q) == ping_trans_color.green && (unsigned short) GetPixelBlue(q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q++; } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->matte; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",image->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->x_resolution != 0) && (image->y_resolution != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->x_resolution+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->y_resolution+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->x_resolution; ping_pHYs_y_resolution=(png_uint_32) image->y_resolution; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorMatteType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteMatteType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, image->colormap))) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) (255- ScaleQuantumToChar(image->colormap[i].opacity)); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)*(ScaleQuantumToShort((Quantum) GetPixelLuma(image,&image->background_color)))+.5); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_background.index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_background.gray is %d\", (int) ping_background.gray); } ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This is addressed by using \"-define png:compression-strategy\", etc., which takes precedence over -quality. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->matte == MagickFalse) { \/* Add an opaque matte channel *\/ image->matte = MagickTrue; (void) SetImageOpacity(image,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { if (mng_info->have_write_global_plte && matte == MagickFalse) { png_set_PLTE(ping,ping_info,NULL,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up empty PLTE chunk\"); } else png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(const png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } else #endif { if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } if (ping_exclude_zCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXT chunk with uuencoded ICC\"); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk with %s profile\",name); name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\"); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; (void) ping_have_blob; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { \/* Palette, Bilevel, or Opaque Monochrome *\/ register const PixelPacket *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { \/* Undo pixel scaling *\/ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\",pass); p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(image,\"png:bit-depth-written\",s); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":424307,"input":"exec_instructions(ectx_T *ectx) { int ret = FAIL; int save_trylevel_at_start = ectx->ec_trylevel_at_start; int dict_stack_len_at_start = dict_stack.ga_len; \/\/ Start execution at the first instruction. ectx->ec_iidx = 0; \/\/ Only catch exceptions in this instruction list. ectx->ec_trylevel_at_start = trylevel; for (;;) { static int breakcheck_count = 0; \/\/ using \"static\" makes it faster isn_T *iptr; typval_T *tv; if (unlikely(++breakcheck_count >= 100)) { line_breakcheck(); breakcheck_count = 0; } if (unlikely(got_int)) { \/\/ Turn CTRL-C into an exception. got_int = FALSE; if (throw_exception(\"Vim:Interrupt\", ET_INTERRUPT, NULL) == FAIL) goto theend; did_throw = TRUE; } if (unlikely(did_emsg && msg_list != NULL && *msg_list != NULL)) { \/\/ Turn an error message into an exception. did_emsg = FALSE; if (throw_exception(*msg_list, ET_ERROR, NULL) == FAIL) goto theend; did_throw = TRUE; *msg_list = NULL; } if (unlikely(did_throw)) { garray_T *trystack = &ectx->ec_trystack; trycmd_T *trycmd = NULL; int index = trystack->ga_len; \/\/ An exception jumps to the first catch, finally, or returns from \/\/ the current function. while (index > 0) { trycmd = ((trycmd_T *)trystack->ga_data) + index - 1; if (!trycmd->tcd_in_catch || trycmd->tcd_finally_idx != 0) break; \/\/ In the catch and finally block of this try we have to go up \/\/ one level. --index; trycmd = NULL; } if (trycmd != NULL && trycmd->tcd_frame_idx == ectx->ec_frame_idx) { if (trycmd->tcd_in_catch) { \/\/ exception inside \":catch\", jump to \":finally\" once ectx->ec_iidx = trycmd->tcd_finally_idx; trycmd->tcd_finally_idx = 0; } else \/\/ jump to first \":catch\" ectx->ec_iidx = trycmd->tcd_catch_idx; trycmd->tcd_in_catch = TRUE; did_throw = FALSE; \/\/ don't come back here until :endtry trycmd->tcd_did_throw = TRUE; } else { \/\/ Not inside try or need to return from current functions. \/\/ Push a dummy return value. if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->v_type = VAR_NUMBER; tv->vval.v_number = 0; ++ectx->ec_stack.ga_len; if (ectx->ec_frame_idx == ectx->ec_initial_frame_idx) { \/\/ At the toplevel we are done. need_rethrow = TRUE; if (handle_closure_in_use(ectx, FALSE) == FAIL) goto theend; goto done; } if (func_return(ectx) == FAIL) goto theend; } continue; } iptr = &ectx->ec_instr[ectx->ec_iidx++]; switch (iptr->isn_type) { \/\/ execute Ex command line case ISN_EXEC: if (exec_command(iptr) == FAIL) goto on_error; break; \/\/ execute Ex command line split at NL characters. case ISN_EXEC_SPLIT: { source_cookie_T cookie; char_u *line; SOURCING_LNUM = iptr->isn_lnum; CLEAR_FIELD(cookie); cookie.sourcing_lnum = iptr->isn_lnum - 1; cookie.nextline = iptr->isn_arg.string; line = get_split_sourceline(0, &cookie, 0, 0); if (do_cmdline(line, get_split_sourceline, &cookie, DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED) == FAIL || did_emsg) { vim_free(line); goto on_error; } vim_free(line); } break; \/\/ execute Ex command line that is only a range case ISN_EXECRANGE: { exarg_T ea; char *error = NULL; CLEAR_FIELD(ea); ea.cmdidx = CMD_SIZE; ea.addr_type = ADDR_LINES; ea.cmd = iptr->isn_arg.string; parse_cmd_address(&ea, &error, FALSE); if (ea.cmd == NULL) goto on_error; if (error == NULL) error = ex_range_without_command(&ea); if (error != NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(error); goto on_error; } } break; \/\/ Evaluate an expression with legacy syntax, push it onto the \/\/ stack. case ISN_LEGACY_EVAL: { char_u *arg = iptr->isn_arg.string; int res; int save_flags = cmdmod.cmod_flags; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); init_tv(tv); cmdmod.cmod_flags |= CMOD_LEGACY; res = eval0(arg, tv, NULL, &EVALARG_EVALUATE); cmdmod.cmod_flags = save_flags; if (res == FAIL) goto on_error; ++ectx->ec_stack.ga_len; } break; \/\/ push typeval VAR_INSTR with instructions to be executed case ISN_INSTR: { if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->vval.v_instr = ALLOC_ONE(instr_T); if (tv->vval.v_instr == NULL) goto on_error; ++ectx->ec_stack.ga_len; tv->v_type = VAR_INSTR; tv->vval.v_instr->instr_ectx = ectx; tv->vval.v_instr->instr_instr = iptr->isn_arg.instr; } break; \/\/ execute :substitute with an expression case ISN_SUBSTITUTE: { subs_T *subs = &iptr->isn_arg.subs; source_cookie_T cookie; struct subs_expr_S *save_instr = substitute_instr; struct subs_expr_S subs_instr; int res; subs_instr.subs_ectx = ectx; subs_instr.subs_instr = subs->subs_instr; subs_instr.subs_status = OK; substitute_instr = &subs_instr; SOURCING_LNUM = iptr->isn_lnum; \/\/ This is very much like ISN_EXEC CLEAR_FIELD(cookie); cookie.sourcing_lnum = iptr->isn_lnum - 1; res = do_cmdline(subs->subs_cmd, getsourceline, &cookie, DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED); substitute_instr = save_instr; if (res == FAIL || did_emsg || subs_instr.subs_status == FAIL) goto on_error; } break; case ISN_FINISH: goto done; case ISN_REDIRSTART: \/\/ create a dummy entry for var_redir_str() if (alloc_redir_lval() == FAIL) goto on_error; \/\/ The output is stored in growarray \"redir_ga\" until \/\/ redirection ends. init_redir_ga(); redir_vname = 1; break; case ISN_REDIREND: { char_u *res = get_clear_redir_ga(); \/\/ End redirection, put redirected text on the stack. clear_redir_lval(); redir_vname = 0; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) { vim_free(res); goto theend; } tv = STACK_TV_BOT(0); tv->v_type = VAR_STRING; tv->vval.v_string = res; ++ectx->ec_stack.ga_len; } break; case ISN_CEXPR_AUCMD: #ifdef FEAT_QUICKFIX if (trigger_cexpr_autocmd(iptr->isn_arg.number) == FAIL) goto on_error; #endif break; case ISN_CEXPR_CORE: #ifdef FEAT_QUICKFIX { exarg_T ea; int res; CLEAR_FIELD(ea); ea.cmdidx = iptr->isn_arg.cexpr.cexpr_ref->cer_cmdidx; ea.forceit = iptr->isn_arg.cexpr.cexpr_ref->cer_forceit; ea.cmdlinep = &iptr->isn_arg.cexpr.cexpr_ref->cer_cmdline; --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); res = cexpr_core(&ea, tv); clear_tv(tv); if (res == FAIL) goto on_error; } #endif break; \/\/ execute Ex command from pieces on the stack case ISN_EXECCONCAT: { int count = iptr->isn_arg.number; size_t len = 0; int pass; int i; char_u *cmd = NULL; char_u *str; for (pass = 1; pass <= 2; ++pass) { for (i = 0; i < count; ++i) { tv = STACK_TV_BOT(i - count); str = tv->vval.v_string; if (str != NULL && *str != NUL) { if (pass == 2) STRCPY(cmd + len, str); len += STRLEN(str); } if (pass == 2) clear_tv(tv); } if (pass == 1) { cmd = alloc(len + 1); if (unlikely(cmd == NULL)) goto theend; len = 0; } } SOURCING_LNUM = iptr->isn_lnum; do_cmdline_cmd(cmd); vim_free(cmd); } break; \/\/ execute :echo {string} ... case ISN_ECHO: { int count = iptr->isn_arg.echo.echo_count; int atstart = TRUE; int needclr = TRUE; int idx; for (idx = 0; idx < count; ++idx) { tv = STACK_TV_BOT(idx - count); echo_one(tv, iptr->isn_arg.echo.echo_with_white, &atstart, &needclr); clear_tv(tv); } if (needclr) msg_clr_eos(); ectx->ec_stack.ga_len -= count; } break; \/\/ :execute {string} ... \/\/ :echomsg {string} ... \/\/ :echoconsole {string} ... \/\/ :echoerr {string} ... case ISN_EXECUTE: case ISN_ECHOMSG: case ISN_ECHOCONSOLE: case ISN_ECHOERR: { int count = iptr->isn_arg.number; garray_T ga; char_u buf[NUMBUFLEN]; char_u *p; int len; int failed = FALSE; int idx; ga_init2(&ga, 1, 80); for (idx = 0; idx < count; ++idx) { tv = STACK_TV_BOT(idx - count); if (iptr->isn_type == ISN_EXECUTE) { if (tv->v_type == VAR_CHANNEL || tv->v_type == VAR_JOB) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_using_invalid_value_as_string_str), vartype_name(tv->v_type)); break; } else p = tv_get_string_buf(tv, buf); } else p = tv_stringify(tv, buf); len = (int)STRLEN(p); if (GA_GROW_FAILS(&ga, len + 2)) failed = TRUE; else { if (ga.ga_len > 0) ((char_u *)(ga.ga_data))[ga.ga_len++] = ' '; STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p); ga.ga_len += len; } clear_tv(tv); } ectx->ec_stack.ga_len -= count; if (failed) { ga_clear(&ga); goto on_error; } if (ga.ga_data != NULL) { if (iptr->isn_type == ISN_EXECUTE) { SOURCING_LNUM = iptr->isn_lnum; do_cmdline_cmd((char_u *)ga.ga_data); if (did_emsg) { ga_clear(&ga); goto on_error; } } else { msg_sb_eol(); if (iptr->isn_type == ISN_ECHOMSG) { msg_attr(ga.ga_data, echo_attr); out_flush(); } else if (iptr->isn_type == ISN_ECHOCONSOLE) { ui_write(ga.ga_data, (int)STRLEN(ga.ga_data), TRUE); ui_write((char_u *)\"\\r\\n\", 2, TRUE); } else { SOURCING_LNUM = iptr->isn_lnum; emsg(ga.ga_data); } } } ga_clear(&ga); } break; \/\/ load local variable or argument case ISN_LOAD: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(STACK_TV_VAR(iptr->isn_arg.number), STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; break; \/\/ load v: variable case ISN_LOADV: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(get_vim_var_tv(iptr->isn_arg.number), STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; break; \/\/ load s: variable in Vim9 script case ISN_LOADSCRIPT: { scriptref_T *sref = iptr->isn_arg.script.scriptref; svar_T *sv; sv = get_script_svar(sref, ectx->ec_dfunc_idx); if (sv == NULL) goto theend; allocate_if_null(sv->sv_tv); if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(sv->sv_tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } break; \/\/ load s: variable in old script case ISN_LOADS: { hashtab_T *ht = &SCRIPT_VARS( iptr->isn_arg.loadstore.ls_sid); char_u *name = iptr->isn_arg.loadstore.ls_name; dictitem_T *di = find_var_in_ht(ht, 0, name, TRUE); if (di == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_undefined_variable_str), name); goto on_error; } else { if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(&di->di_tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } } break; \/\/ load g:\/b:\/w:\/t: variable case ISN_LOADG: case ISN_LOADB: case ISN_LOADW: case ISN_LOADT: { dictitem_T *di = NULL; hashtab_T *ht = NULL; char namespace; switch (iptr->isn_type) { case ISN_LOADG: ht = get_globvar_ht(); namespace = 'g'; break; case ISN_LOADB: ht = &curbuf->b_vars->dv_hashtab; namespace = 'b'; break; case ISN_LOADW: ht = &curwin->w_vars->dv_hashtab; namespace = 'w'; break; case ISN_LOADT: ht = &curtab->tp_vars->dv_hashtab; namespace = 't'; break; default: \/\/ Cannot reach here goto theend; } di = find_var_in_ht(ht, 0, iptr->isn_arg.string, TRUE); if (di == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_undefined_variable_char_str), namespace, iptr->isn_arg.string); goto on_error; } else { if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(&di->di_tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } } break; \/\/ load autoload variable case ISN_LOADAUTO: { char_u *name = iptr->isn_arg.string; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; SOURCING_LNUM = iptr->isn_lnum; if (eval_variable(name, (int)STRLEN(name), 0, STACK_TV_BOT(0), NULL, EVAL_VAR_VERBOSE) == FAIL) goto on_error; ++ectx->ec_stack.ga_len; } break; \/\/ load g:\/b:\/w:\/t: namespace case ISN_LOADGDICT: case ISN_LOADBDICT: case ISN_LOADWDICT: case ISN_LOADTDICT: { dict_T *d = NULL; switch (iptr->isn_type) { case ISN_LOADGDICT: d = get_globvar_dict(); break; case ISN_LOADBDICT: d = curbuf->b_vars; break; case ISN_LOADWDICT: d = curwin->w_vars; break; case ISN_LOADTDICT: d = curtab->tp_vars; break; default: \/\/ Cannot reach here goto theend; } if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->v_type = VAR_DICT; tv->v_lock = 0; tv->vval.v_dict = d; ++d->dv_refcount; ++ectx->ec_stack.ga_len; } break; \/\/ load &option case ISN_LOADOPT: { typval_T optval; char_u *name = iptr->isn_arg.string; \/\/ This is not expected to fail, name is checked during \/\/ compilation: don't set SOURCING_LNUM. if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; if (eval_option(&name, &optval, TRUE) == FAIL) goto theend; *STACK_TV_BOT(0) = optval; ++ectx->ec_stack.ga_len; } break; \/\/ load $ENV case ISN_LOADENV: { typval_T optval; char_u *name = iptr->isn_arg.string; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; \/\/ name is always valid, checked when compiling (void)eval_env_var(&name, &optval, TRUE); *STACK_TV_BOT(0) = optval; ++ectx->ec_stack.ga_len; } break; \/\/ load @register case ISN_LOADREG: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->v_type = VAR_STRING; tv->v_lock = 0; \/\/ This may result in NULL, which should be equivalent to an \/\/ empty string. tv->vval.v_string = get_reg_contents( iptr->isn_arg.number, GREG_EXPR_SRC); ++ectx->ec_stack.ga_len; break; \/\/ store local variable case ISN_STORE: --ectx->ec_stack.ga_len; tv = STACK_TV_VAR(iptr->isn_arg.number); clear_tv(tv); *tv = *STACK_TV_BOT(0); break; \/\/ store s: variable in old script case ISN_STORES: { hashtab_T *ht = &SCRIPT_VARS( iptr->isn_arg.loadstore.ls_sid); char_u *name = iptr->isn_arg.loadstore.ls_name; dictitem_T *di = find_var_in_ht(ht, 0, name + 2, TRUE); --ectx->ec_stack.ga_len; if (di == NULL) store_var(name, STACK_TV_BOT(0)); else { SOURCING_LNUM = iptr->isn_lnum; if (var_check_permission(di, name) == FAIL) { clear_tv(STACK_TV_BOT(0)); goto on_error; } clear_tv(&di->di_tv); di->di_tv = *STACK_TV_BOT(0); } } break; \/\/ store script-local variable in Vim9 script case ISN_STORESCRIPT: { scriptref_T *sref = iptr->isn_arg.script.scriptref; svar_T *sv; sv = get_script_svar(sref, ectx->ec_dfunc_idx); if (sv == NULL) goto theend; --ectx->ec_stack.ga_len; \/\/ \"const\" and \"final\" are checked at compile time, locking \/\/ the value needs to be checked here. SOURCING_LNUM = iptr->isn_lnum; if (value_check_lock(sv->sv_tv->v_lock, sv->sv_name, FALSE)) { clear_tv(STACK_TV_BOT(0)); goto on_error; } clear_tv(sv->sv_tv); *sv->sv_tv = *STACK_TV_BOT(0); } break; \/\/ store option case ISN_STOREOPT: case ISN_STOREFUNCOPT: { char_u *opt_name = iptr->isn_arg.storeopt.so_name; int opt_flags = iptr->isn_arg.storeopt.so_flags; long n = 0; char_u *s = NULL; char *msg; char_u numbuf[NUMBUFLEN]; char_u *tofree = NULL; --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); if (tv->v_type == VAR_STRING) { s = tv->vval.v_string; if (s == NULL) s = (char_u *)\"\"; } else if (iptr->isn_type == ISN_STOREFUNCOPT) { SOURCING_LNUM = iptr->isn_lnum; \/\/ If the option can be set to a function reference or \/\/ a lambda and the passed value is a function \/\/ reference, then convert it to the name (string) of \/\/ the function reference. s = tv2string(tv, &tofree, numbuf, 0); if (s == NULL || *s == NUL) { clear_tv(tv); goto on_error; } } else \/\/ must be VAR_NUMBER, CHECKTYPE makes sure n = tv->vval.v_number; msg = set_option_value(opt_name, n, s, opt_flags); clear_tv(tv); vim_free(tofree); if (msg != NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(msg)); goto on_error; } } break; \/\/ store $ENV case ISN_STOREENV: --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); vim_setenv_ext(iptr->isn_arg.string, tv_get_string(tv)); clear_tv(tv); break; \/\/ store @r case ISN_STOREREG: { int reg = iptr->isn_arg.number; --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); write_reg_contents(reg, tv_get_string(tv), -1, FALSE); clear_tv(tv); } break; \/\/ store v: variable case ISN_STOREV: --ectx->ec_stack.ga_len; if (set_vim_var_tv(iptr->isn_arg.number, STACK_TV_BOT(0)) == FAIL) \/\/ should not happen, type is checked when compiling goto on_error; break; \/\/ store g:\/b:\/w:\/t: variable case ISN_STOREG: case ISN_STOREB: case ISN_STOREW: case ISN_STORET: { dictitem_T *di; hashtab_T *ht; char_u *name = iptr->isn_arg.string + 2; switch (iptr->isn_type) { case ISN_STOREG: ht = get_globvar_ht(); break; case ISN_STOREB: ht = &curbuf->b_vars->dv_hashtab; break; case ISN_STOREW: ht = &curwin->w_vars->dv_hashtab; break; case ISN_STORET: ht = &curtab->tp_vars->dv_hashtab; break; default: \/\/ Cannot reach here goto theend; } --ectx->ec_stack.ga_len; di = find_var_in_ht(ht, 0, name, TRUE); if (di == NULL) store_var(iptr->isn_arg.string, STACK_TV_BOT(0)); else { SOURCING_LNUM = iptr->isn_lnum; if (var_check_permission(di, name) == FAIL) goto on_error; clear_tv(&di->di_tv); di->di_tv = *STACK_TV_BOT(0); } } break; \/\/ store an autoload variable case ISN_STOREAUTO: SOURCING_LNUM = iptr->isn_lnum; set_var(iptr->isn_arg.string, STACK_TV_BOT(-1), TRUE); clear_tv(STACK_TV_BOT(-1)); --ectx->ec_stack.ga_len; break; \/\/ store number in local variable case ISN_STORENR: tv = STACK_TV_VAR(iptr->isn_arg.storenr.stnr_idx); clear_tv(tv); tv->v_type = VAR_NUMBER; tv->vval.v_number = iptr->isn_arg.storenr.stnr_val; break; \/\/ store value in list or dict variable case ISN_STOREINDEX: { vartype_T dest_type = iptr->isn_arg.vartype; typval_T *tv_idx = STACK_TV_BOT(-2); typval_T *tv_dest = STACK_TV_BOT(-1); int status = OK; \/\/ Stack contains: \/\/ -3 value to be stored \/\/ -2 index \/\/ -1 dict or list tv = STACK_TV_BOT(-3); SOURCING_LNUM = iptr->isn_lnum; if (dest_type == VAR_ANY) { dest_type = tv_dest->v_type; if (dest_type == VAR_DICT) status = do_2string(tv_idx, TRUE, FALSE); else if (dest_type == VAR_LIST && tv_idx->v_type != VAR_NUMBER) { emsg(_(e_number_expected)); status = FAIL; } } else if (dest_type != tv_dest->v_type) { \/\/ just in case, should be OK semsg(_(e_expected_str_but_got_str), vartype_name(dest_type), vartype_name(tv_dest->v_type)); status = FAIL; } if (status == OK && dest_type == VAR_LIST) { long lidx = (long)tv_idx->vval.v_number; list_T *list = tv_dest->vval.v_list; if (list == NULL) { emsg(_(e_list_not_set)); goto on_error; } if (lidx < 0 && list->lv_len + lidx >= 0) \/\/ negative index is relative to the end lidx = list->lv_len + lidx; if (lidx < 0 || lidx > list->lv_len) { semsg(_(e_list_index_out_of_range_nr), lidx); goto on_error; } if (lidx < list->lv_len) { listitem_T *li = list_find(list, lidx); if (error_if_locked(li->li_tv.v_lock, e_cannot_change_list_item)) goto on_error; \/\/ overwrite existing list item clear_tv(&li->li_tv); li->li_tv = *tv; } else { if (error_if_locked(list->lv_lock, e_cannot_change_list)) goto on_error; \/\/ append to list, only fails when out of memory if (list_append_tv(list, tv) == FAIL) goto theend; clear_tv(tv); } } else if (status == OK && dest_type == VAR_DICT) { char_u *key = tv_idx->vval.v_string; dict_T *dict = tv_dest->vval.v_dict; dictitem_T *di; SOURCING_LNUM = iptr->isn_lnum; if (dict == NULL) { emsg(_(e_dictionary_not_set)); goto on_error; } if (key == NULL) key = (char_u *)\"\"; di = dict_find(dict, key, -1); if (di != NULL) { if (error_if_locked(di->di_tv.v_lock, e_cannot_change_dict_item)) goto on_error; \/\/ overwrite existing value clear_tv(&di->di_tv); di->di_tv = *tv; } else { if (error_if_locked(dict->dv_lock, e_cannot_change_dict)) goto on_error; \/\/ add to dict, only fails when out of memory if (dict_add_tv(dict, (char *)key, tv) == FAIL) goto theend; clear_tv(tv); } } else if (status == OK && dest_type == VAR_BLOB) { long lidx = (long)tv_idx->vval.v_number; blob_T *blob = tv_dest->vval.v_blob; varnumber_T nr; int error = FALSE; int len; if (blob == NULL) { emsg(_(e_blob_not_set)); goto on_error; } len = blob_len(blob); if (lidx < 0 && len + lidx >= 0) \/\/ negative index is relative to the end lidx = len + lidx; \/\/ Can add one byte at the end. if (lidx < 0 || lidx > len) { semsg(_(e_blob_index_out_of_range_nr), lidx); goto on_error; } if (value_check_lock(blob->bv_lock, (char_u *)\"blob\", FALSE)) goto on_error; nr = tv_get_number_chk(tv, &error); if (error) goto on_error; blob_set_append(blob, lidx, nr); } else { status = FAIL; semsg(_(e_cannot_index_str), vartype_name(dest_type)); } clear_tv(tv_idx); clear_tv(tv_dest); ectx->ec_stack.ga_len -= 3; if (status == FAIL) { clear_tv(tv); goto on_error; } } break; \/\/ store value in blob range case ISN_STORERANGE: { typval_T *tv_idx1 = STACK_TV_BOT(-3); typval_T *tv_idx2 = STACK_TV_BOT(-2); typval_T *tv_dest = STACK_TV_BOT(-1); int status = OK; \/\/ Stack contains: \/\/ -4 value to be stored \/\/ -3 first index or \"none\" \/\/ -2 second index or \"none\" \/\/ -1 destination list or blob tv = STACK_TV_BOT(-4); if (tv_dest->v_type == VAR_LIST) { long n1; long n2; int error = FALSE; SOURCING_LNUM = iptr->isn_lnum; n1 = (long)tv_get_number_chk(tv_idx1, &error); if (error) status = FAIL; else { if (tv_idx2->v_type == VAR_SPECIAL && tv_idx2->vval.v_number == VVAL_NONE) n2 = list_len(tv_dest->vval.v_list) - 1; else n2 = (long)tv_get_number_chk(tv_idx2, &error); if (error) status = FAIL; else { listitem_T *li1 = check_range_index_one( tv_dest->vval.v_list, &n1, FALSE); if (li1 == NULL) status = FAIL; else { status = check_range_index_two( tv_dest->vval.v_list, &n1, li1, &n2, FALSE); if (status != FAIL) status = list_assign_range( tv_dest->vval.v_list, tv->vval.v_list, n1, n2, tv_idx2->v_type == VAR_SPECIAL, (char_u *)\"=\", (char_u *)\"[unknown]\"); } } } } else if (tv_dest->v_type == VAR_BLOB) { varnumber_T n1; varnumber_T n2; int error = FALSE; n1 = tv_get_number_chk(tv_idx1, &error); if (error) status = FAIL; else { if (tv_idx2->v_type == VAR_SPECIAL && tv_idx2->vval.v_number == VVAL_NONE) n2 = blob_len(tv_dest->vval.v_blob) - 1; else n2 = tv_get_number_chk(tv_idx2, &error); if (error) status = FAIL; else { long bloblen = blob_len(tv_dest->vval.v_blob); if (check_blob_index(bloblen, n1, FALSE) == FAIL || check_blob_range(bloblen, n1, n2, FALSE) == FAIL) status = FAIL; else status = blob_set_range( tv_dest->vval.v_blob, n1, n2, tv); } } } else { status = FAIL; emsg(_(e_blob_required)); } clear_tv(tv_idx1); clear_tv(tv_idx2); clear_tv(tv_dest); ectx->ec_stack.ga_len -= 4; clear_tv(tv); if (status == FAIL) goto on_error; } break; \/\/ load or store variable or argument from outer scope case ISN_LOADOUTER: case ISN_STOREOUTER: { int depth = iptr->isn_arg.outer.outer_depth; outer_T *outer = ectx->ec_outer_ref == NULL ? NULL : ectx->ec_outer_ref->or_outer; while (depth > 1 && outer != NULL) { outer = outer->out_up; --depth; } if (outer == NULL) { SOURCING_LNUM = iptr->isn_lnum; if (ectx->ec_frame_idx == ectx->ec_initial_frame_idx || ectx->ec_outer_ref == NULL) \/\/ Possibly :def function called from legacy \/\/ context. emsg(_(e_closure_called_from_invalid_context)); else iemsg(\"LOADOUTER depth more than scope levels\"); goto theend; } tv = ((typval_T *)outer->out_stack->ga_data) + outer->out_frame_idx + STACK_FRAME_SIZE + iptr->isn_arg.outer.outer_idx; if (iptr->isn_type == ISN_LOADOUTER) { if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } else { --ectx->ec_stack.ga_len; clear_tv(tv); *tv = *STACK_TV_BOT(0); } } break; \/\/ unlet item in list or dict variable case ISN_UNLETINDEX: { typval_T *tv_idx = STACK_TV_BOT(-2); typval_T *tv_dest = STACK_TV_BOT(-1); int status = OK; \/\/ Stack contains: \/\/ -2 index \/\/ -1 dict or list if (tv_dest->v_type == VAR_DICT) { \/\/ unlet a dict item, index must be a string if (tv_idx->v_type != VAR_STRING) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_expected_str_but_got_str), vartype_name(VAR_STRING), vartype_name(tv_idx->v_type)); status = FAIL; } else { dict_T *d = tv_dest->vval.v_dict; char_u *key = tv_idx->vval.v_string; dictitem_T *di = NULL; if (d != NULL && value_check_lock( d->dv_lock, NULL, FALSE)) status = FAIL; else { SOURCING_LNUM = iptr->isn_lnum; if (key == NULL) key = (char_u *)\"\"; if (d != NULL) di = dict_find(d, key, (int)STRLEN(key)); if (di == NULL) { \/\/ NULL dict is equivalent to empty dict semsg(_(e_key_not_present_in_dictionary), key); status = FAIL; } else if (var_check_fixed(di->di_flags, NULL, FALSE) || var_check_ro(di->di_flags, NULL, FALSE)) status = FAIL; else dictitem_remove(d, di); } } } else if (tv_dest->v_type == VAR_LIST) { \/\/ unlet a List item, index must be a number SOURCING_LNUM = iptr->isn_lnum; if (check_for_number(tv_idx) == FAIL) { status = FAIL; } else { list_T *l = tv_dest->vval.v_list; long n = (long)tv_idx->vval.v_number; if (l != NULL && value_check_lock( l->lv_lock, NULL, FALSE)) status = FAIL; else { listitem_T *li = list_find(l, n); if (li == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_list_index_out_of_range_nr), n); status = FAIL; } else if (value_check_lock(li->li_tv.v_lock, NULL, FALSE)) status = FAIL; else listitem_remove(l, li); } } } else { status = FAIL; semsg(_(e_cannot_index_str), vartype_name(tv_dest->v_type)); } clear_tv(tv_idx); clear_tv(tv_dest); ectx->ec_stack.ga_len -= 2; if (status == FAIL) goto on_error; } break; \/\/ unlet range of items in list variable case ISN_UNLETRANGE: { \/\/ Stack contains: \/\/ -3 index1 \/\/ -2 index2 \/\/ -1 dict or list typval_T *tv_idx1 = STACK_TV_BOT(-3); typval_T *tv_idx2 = STACK_TV_BOT(-2); typval_T *tv_dest = STACK_TV_BOT(-1); int status = OK; if (tv_dest->v_type == VAR_LIST) { \/\/ indexes must be a number SOURCING_LNUM = iptr->isn_lnum; if (check_for_number(tv_idx1) == FAIL || (tv_idx2->v_type != VAR_SPECIAL && check_for_number(tv_idx2) == FAIL)) { status = FAIL; } else { list_T *l = tv_dest->vval.v_list; long n1 = (long)tv_idx1->vval.v_number; long n2 = tv_idx2->v_type == VAR_SPECIAL ? 0 : (long)tv_idx2->vval.v_number; listitem_T *li; li = list_find_index(l, &n1); if (li == NULL) status = FAIL; else { if (n1 < 0) n1 = list_idx_of_item(l, li); if (n2 < 0) { listitem_T *li2 = list_find(l, n2); if (li2 == NULL) status = FAIL; else n2 = list_idx_of_item(l, li2); } if (status != FAIL && tv_idx2->v_type != VAR_SPECIAL && n2 < n1) { semsg(_(e_list_index_out_of_range_nr), n2); status = FAIL; } if (status != FAIL && list_unlet_range(l, li, NULL, n1, tv_idx2->v_type != VAR_SPECIAL, n2) == FAIL) status = FAIL; } } } else { status = FAIL; SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_cannot_index_str), vartype_name(tv_dest->v_type)); } clear_tv(tv_idx1); clear_tv(tv_idx2); clear_tv(tv_dest); ectx->ec_stack.ga_len -= 3; if (status == FAIL) goto on_error; } break; \/\/ push constant case ISN_PUSHNR: case ISN_PUSHBOOL: case ISN_PUSHSPEC: case ISN_PUSHF: case ISN_PUSHS: case ISN_PUSHBLOB: case ISN_PUSHFUNC: case ISN_PUSHCHANNEL: case ISN_PUSHJOB: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->v_lock = 0; ++ectx->ec_stack.ga_len; switch (iptr->isn_type) { case ISN_PUSHNR: tv->v_type = VAR_NUMBER; tv->vval.v_number = iptr->isn_arg.number; break; case ISN_PUSHBOOL: tv->v_type = VAR_BOOL; tv->vval.v_number = iptr->isn_arg.number; break; case ISN_PUSHSPEC: tv->v_type = VAR_SPECIAL; tv->vval.v_number = iptr->isn_arg.number; break; #ifdef FEAT_FLOAT case ISN_PUSHF: tv->v_type = VAR_FLOAT; tv->vval.v_float = iptr->isn_arg.fnumber; break; #endif case ISN_PUSHBLOB: blob_copy(iptr->isn_arg.blob, tv); break; case ISN_PUSHFUNC: tv->v_type = VAR_FUNC; if (iptr->isn_arg.string == NULL) tv->vval.v_string = NULL; else tv->vval.v_string = vim_strsave(iptr->isn_arg.string); break; case ISN_PUSHCHANNEL: #ifdef FEAT_JOB_CHANNEL tv->v_type = VAR_CHANNEL; tv->vval.v_channel = iptr->isn_arg.channel; if (tv->vval.v_channel != NULL) ++tv->vval.v_channel->ch_refcount; #endif break; case ISN_PUSHJOB: #ifdef FEAT_JOB_CHANNEL tv->v_type = VAR_JOB; tv->vval.v_job = iptr->isn_arg.job; if (tv->vval.v_job != NULL) ++tv->vval.v_job->jv_refcount; #endif break; default: tv->v_type = VAR_STRING; tv->vval.v_string = vim_strsave( iptr->isn_arg.string == NULL ? (char_u *)\"\" : iptr->isn_arg.string); } break; case ISN_UNLET: if (do_unlet(iptr->isn_arg.unlet.ul_name, iptr->isn_arg.unlet.ul_forceit) == FAIL) goto on_error; break; case ISN_UNLETENV: vim_unsetenv(iptr->isn_arg.unlet.ul_name); break; case ISN_LOCKUNLOCK: { typval_T *lval_root_save = lval_root; int res; \/\/ Stack has the local variable, argument the whole :lock \/\/ or :unlock command, like ISN_EXEC. --ectx->ec_stack.ga_len; lval_root = STACK_TV_BOT(0); res = exec_command(iptr); clear_tv(lval_root); lval_root = lval_root_save; if (res == FAIL) goto on_error; } break; case ISN_LOCKCONST: item_lock(STACK_TV_BOT(-1), 100, TRUE, TRUE); break; \/\/ create a list from items on the stack; uses a single allocation \/\/ for the list header and the items case ISN_NEWLIST: if (exe_newlist(iptr->isn_arg.number, ectx) == FAIL) goto theend; break; \/\/ create a dict from items on the stack case ISN_NEWDICT: { int count = iptr->isn_arg.number; dict_T *dict = dict_alloc(); dictitem_T *item; char_u *key; int idx; if (unlikely(dict == NULL)) goto theend; for (idx = 0; idx < count; ++idx) { \/\/ have already checked key type is VAR_STRING tv = STACK_TV_BOT(2 * (idx - count)); \/\/ check key is unique key = tv->vval.v_string == NULL ? (char_u *)\"\" : tv->vval.v_string; item = dict_find(dict, key, -1); if (item != NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_duplicate_key_in_dicitonary), key); dict_unref(dict); goto on_error; } item = dictitem_alloc(key); clear_tv(tv); if (unlikely(item == NULL)) { dict_unref(dict); goto theend; } item->di_tv = *STACK_TV_BOT(2 * (idx - count) + 1); item->di_tv.v_lock = 0; if (dict_add(dict, item) == FAIL) { \/\/ can this ever happen? dict_unref(dict); goto theend; } } if (count > 0) ectx->ec_stack.ga_len -= 2 * count - 1; else if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; else ++ectx->ec_stack.ga_len; tv = STACK_TV_BOT(-1); tv->v_type = VAR_DICT; tv->v_lock = 0; tv->vval.v_dict = dict; ++dict->dv_refcount; } break; \/\/ call a :def function case ISN_DCALL: SOURCING_LNUM = iptr->isn_lnum; if (call_dfunc(iptr->isn_arg.dfunc.cdf_idx, NULL, iptr->isn_arg.dfunc.cdf_argcount, ectx) == FAIL) goto on_error; break; \/\/ call a builtin function case ISN_BCALL: SOURCING_LNUM = iptr->isn_lnum; if (call_bfunc(iptr->isn_arg.bfunc.cbf_idx, iptr->isn_arg.bfunc.cbf_argcount, ectx) == FAIL) goto on_error; break; \/\/ call a funcref or partial case ISN_PCALL: { cpfunc_T *pfunc = &iptr->isn_arg.pfunc; int r; typval_T partial_tv; SOURCING_LNUM = iptr->isn_lnum; if (pfunc->cpf_top) { \/\/ funcref is above the arguments tv = STACK_TV_BOT(-pfunc->cpf_argcount - 1); } else { \/\/ Get the funcref from the stack. --ectx->ec_stack.ga_len; partial_tv = *STACK_TV_BOT(0); tv = &partial_tv; } r = call_partial(tv, pfunc->cpf_argcount, ectx); if (tv == &partial_tv) clear_tv(&partial_tv); if (r == FAIL) goto on_error; } break; case ISN_PCALL_END: \/\/ PCALL finished, arguments have been consumed and replaced by \/\/ the return value. Now clear the funcref from the stack, \/\/ and move the return value in its place. --ectx->ec_stack.ga_len; clear_tv(STACK_TV_BOT(-1)); *STACK_TV_BOT(-1) = *STACK_TV_BOT(0); break; \/\/ call a user defined function or funcref\/partial case ISN_UCALL: { cufunc_T *cufunc = &iptr->isn_arg.ufunc; SOURCING_LNUM = iptr->isn_lnum; if (call_eval_func(cufunc->cuf_name, cufunc->cuf_argcount, ectx, iptr) == FAIL) goto on_error; } break; \/\/ return from a :def function call without a value case ISN_RETURN_VOID: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); ++ectx->ec_stack.ga_len; tv->v_type = VAR_VOID; tv->vval.v_number = 0; tv->v_lock = 0; \/\/ FALLTHROUGH \/\/ return from a :def function call with what is on the stack case ISN_RETURN: { garray_T *trystack = &ectx->ec_trystack; trycmd_T *trycmd = NULL; if (trystack->ga_len > 0) trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - 1; if (trycmd != NULL && trycmd->tcd_frame_idx == ectx->ec_frame_idx) { \/\/ jump to \":finally\" or \":endtry\" if (trycmd->tcd_finally_idx != 0) ectx->ec_iidx = trycmd->tcd_finally_idx; else ectx->ec_iidx = trycmd->tcd_endtry_idx; trycmd->tcd_return = TRUE; } else goto func_return; } break; \/\/ push a partial, a reference to a compiled function case ISN_FUNCREF: { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); ufunc_T *ufunc; funcref_T *funcref = &iptr->isn_arg.funcref; if (pt == NULL) goto theend; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) { vim_free(pt); goto theend; } if (funcref->fr_func_name == NULL) { dfunc_T *pt_dfunc = ((dfunc_T *)def_functions.ga_data) + funcref->fr_dfunc_idx; ufunc = pt_dfunc->df_ufunc; } else { ufunc = find_func(funcref->fr_func_name, FALSE, NULL); } if (ufunc == NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_function_reference_invalid)); goto theend; } if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) goto theend; tv = STACK_TV_BOT(0); ++ectx->ec_stack.ga_len; tv->vval.v_partial = pt; tv->v_type = VAR_PARTIAL; tv->v_lock = 0; } break; \/\/ Create a global function from a lambda. case ISN_NEWFUNC: { newfunc_T *newfunc = &iptr->isn_arg.newfunc; if (copy_func(newfunc->nf_lambda, newfunc->nf_global, ectx) == FAIL) goto theend; } break; \/\/ List functions case ISN_DEF: if (iptr->isn_arg.string == NULL) list_functions(NULL); else { exarg_T ea; garray_T lines_to_free; CLEAR_FIELD(ea); ea.cmd = ea.arg = iptr->isn_arg.string; ga_init2(&lines_to_free, sizeof(char_u *), 50); define_function(&ea, NULL, &lines_to_free); ga_clear_strings(&lines_to_free); } break; \/\/ jump if a condition is met case ISN_JUMP: { jumpwhen_T when = iptr->isn_arg.jump.jump_when; int error = FALSE; int jump = TRUE; if (when != JUMP_ALWAYS) { tv = STACK_TV_BOT(-1); if (when == JUMP_IF_COND_FALSE || when == JUMP_IF_FALSE || when == JUMP_IF_COND_TRUE) { SOURCING_LNUM = iptr->isn_lnum; jump = tv_get_bool_chk(tv, &error); if (error) goto on_error; } else jump = tv2bool(tv); if (when == JUMP_IF_FALSE || when == JUMP_AND_KEEP_IF_FALSE || when == JUMP_IF_COND_FALSE) jump = !jump; if (when == JUMP_IF_FALSE || !jump) { \/\/ drop the value from the stack clear_tv(tv); --ectx->ec_stack.ga_len; } } if (jump) ectx->ec_iidx = iptr->isn_arg.jump.jump_where; } break; \/\/ Jump if an argument with a default value was already set and not \/\/ v:none. case ISN_JUMP_IF_ARG_SET: tv = STACK_TV_VAR(iptr->isn_arg.jumparg.jump_arg_off); if (tv->v_type != VAR_UNKNOWN && !(tv->v_type == VAR_SPECIAL && tv->vval.v_number == VVAL_NONE)) ectx->ec_iidx = iptr->isn_arg.jumparg.jump_where; break; \/\/ top of a for loop case ISN_FOR: { typval_T *ltv = STACK_TV_BOT(-1); typval_T *idxtv = STACK_TV_VAR(iptr->isn_arg.forloop.for_idx); if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; if (ltv->v_type == VAR_LIST) { list_T *list = ltv->vval.v_list; \/\/ push the next item from the list ++idxtv->vval.v_number; if (list == NULL || idxtv->vval.v_number >= list->lv_len) { \/\/ past the end of the list, jump to \"endfor\" ectx->ec_iidx = iptr->isn_arg.forloop.for_end; may_restore_cmdmod(&ectx->ec_funclocal); } else if (list->lv_first == &range_list_item) { \/\/ non-materialized range() list tv = STACK_TV_BOT(0); tv->v_type = VAR_NUMBER; tv->v_lock = 0; tv->vval.v_number = list_find_nr( list, idxtv->vval.v_number, NULL); ++ectx->ec_stack.ga_len; } else { listitem_T *li = list_find(list, idxtv->vval.v_number); copy_tv(&li->li_tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } } else if (ltv->v_type == VAR_STRING) { char_u *str = ltv->vval.v_string; \/\/ The index is for the last byte of the previous \/\/ character. ++idxtv->vval.v_number; if (str == NULL || str[idxtv->vval.v_number] == NUL) { \/\/ past the end of the string, jump to \"endfor\" ectx->ec_iidx = iptr->isn_arg.forloop.for_end; may_restore_cmdmod(&ectx->ec_funclocal); } else { int clen = mb_ptr2len(str + idxtv->vval.v_number); \/\/ Push the next character from the string. tv = STACK_TV_BOT(0); tv->v_type = VAR_STRING; tv->vval.v_string = vim_strnsave( str + idxtv->vval.v_number, clen); ++ectx->ec_stack.ga_len; idxtv->vval.v_number += clen - 1; } } else if (ltv->v_type == VAR_BLOB) { blob_T *blob = ltv->vval.v_blob; \/\/ When we get here the first time make a copy of the \/\/ blob, so that the iteration still works when it is \/\/ changed. if (idxtv->vval.v_number == -1 && blob != NULL) { blob_copy(blob, ltv); blob_unref(blob); blob = ltv->vval.v_blob; } \/\/ The index is for the previous byte. ++idxtv->vval.v_number; if (blob == NULL || idxtv->vval.v_number >= blob_len(blob)) { \/\/ past the end of the blob, jump to \"endfor\" ectx->ec_iidx = iptr->isn_arg.forloop.for_end; may_restore_cmdmod(&ectx->ec_funclocal); } else { \/\/ Push the next byte from the blob. tv = STACK_TV_BOT(0); tv->v_type = VAR_NUMBER; tv->vval.v_number = blob_get(blob, idxtv->vval.v_number); ++ectx->ec_stack.ga_len; } } else { semsg(_(e_for_loop_on_str_not_supported), vartype_name(ltv->v_type)); goto theend; } } break; \/\/ start of \":try\" block case ISN_TRY: { trycmd_T *trycmd = NULL; if (GA_GROW_FAILS(&ectx->ec_trystack, 1)) goto theend; trycmd = ((trycmd_T *)ectx->ec_trystack.ga_data) + ectx->ec_trystack.ga_len; ++ectx->ec_trystack.ga_len; ++trylevel; CLEAR_POINTER(trycmd); trycmd->tcd_frame_idx = ectx->ec_frame_idx; trycmd->tcd_stack_len = ectx->ec_stack.ga_len; trycmd->tcd_catch_idx = iptr->isn_arg.tryref.try_ref->try_catch; trycmd->tcd_finally_idx = iptr->isn_arg.tryref.try_ref->try_finally; trycmd->tcd_endtry_idx = iptr->isn_arg.tryref.try_ref->try_endtry; } break; case ISN_PUSHEXC: if (current_exception == NULL) { SOURCING_LNUM = iptr->isn_lnum; iemsg(\"Evaluating catch while current_exception is NULL\"); goto theend; } if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); ++ectx->ec_stack.ga_len; tv->v_type = VAR_STRING; tv->v_lock = 0; tv->vval.v_string = vim_strsave( (char_u *)current_exception->value); break; case ISN_CATCH: { garray_T *trystack = &ectx->ec_trystack; may_restore_cmdmod(&ectx->ec_funclocal); if (trystack->ga_len > 0) { trycmd_T *trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - 1; trycmd->tcd_caught = TRUE; trycmd->tcd_did_throw = FALSE; } did_emsg = got_int = did_throw = FALSE; force_abort = need_rethrow = FALSE; catch_exception(current_exception); } break; case ISN_TRYCONT: { garray_T *trystack = &ectx->ec_trystack; trycont_T *trycont = &iptr->isn_arg.trycont; int i; trycmd_T *trycmd; int iidx = trycont->tct_where; if (trystack->ga_len < trycont->tct_levels) { siemsg(\"TRYCONT: expected %d levels, found %d\", trycont->tct_levels, trystack->ga_len); goto theend; } \/\/ Make :endtry jump to any outer try block and the last \/\/ :endtry inside the loop to the loop start. for (i = trycont->tct_levels; i > 0; --i) { trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - i; \/\/ Add one to tcd_cont to be able to jump to \/\/ instruction with index zero. trycmd->tcd_cont = iidx + 1; iidx = trycmd->tcd_finally_idx == 0 ? trycmd->tcd_endtry_idx : trycmd->tcd_finally_idx; } \/\/ jump to :finally or :endtry of current try statement ectx->ec_iidx = iidx; } break; case ISN_FINALLY: { garray_T *trystack = &ectx->ec_trystack; trycmd_T *trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - 1; \/\/ Reset the index to avoid a return statement jumps here \/\/ again. trycmd->tcd_finally_idx = 0; break; } \/\/ end of \":try\" block case ISN_ENDTRY: { garray_T *trystack = &ectx->ec_trystack; if (trystack->ga_len > 0) { trycmd_T *trycmd; --trystack->ga_len; --trylevel; trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len; if (trycmd->tcd_did_throw) did_throw = TRUE; if (trycmd->tcd_caught && current_exception != NULL) { \/\/ discard the exception if (caught_stack == current_exception) caught_stack = caught_stack->caught; discard_current_exception(); } if (trycmd->tcd_return) goto func_return; while (ectx->ec_stack.ga_len > trycmd->tcd_stack_len) { --ectx->ec_stack.ga_len; clear_tv(STACK_TV_BOT(0)); } if (trycmd->tcd_cont != 0) \/\/ handling :continue: jump to outer try block or \/\/ start of the loop ectx->ec_iidx = trycmd->tcd_cont - 1; } } break; case ISN_THROW: { garray_T *trystack = &ectx->ec_trystack; if (trystack->ga_len == 0 && trylevel == 0 && emsg_silent) { \/\/ throwing an exception while using \"silent!\" causes \/\/ the function to abort but not display an error. tv = STACK_TV_BOT(-1); clear_tv(tv); tv->v_type = VAR_NUMBER; tv->vval.v_number = 0; goto done; } --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); if (tv->vval.v_string == NULL || *skipwhite(tv->vval.v_string) == NUL) { vim_free(tv->vval.v_string); SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_throw_with_empty_string)); goto theend; } \/\/ Inside a \"catch\" we need to first discard the caught \/\/ exception. if (trystack->ga_len > 0) { trycmd_T *trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - 1; if (trycmd->tcd_caught && current_exception != NULL) { \/\/ discard the exception if (caught_stack == current_exception) caught_stack = caught_stack->caught; discard_current_exception(); trycmd->tcd_caught = FALSE; } } if (throw_exception(tv->vval.v_string, ET_USER, NULL) == FAIL) { vim_free(tv->vval.v_string); goto theend; } did_throw = TRUE; } break; \/\/ compare with special values case ISN_COMPAREBOOL: case ISN_COMPARESPECIAL: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); varnumber_T arg1 = tv1->vval.v_number; varnumber_T arg2 = tv2->vval.v_number; int res; switch (iptr->isn_arg.op.op_type) { case EXPR_EQUAL: res = arg1 == arg2; break; case EXPR_NEQUAL: res = arg1 != arg2; break; default: res = 0; break; } --ectx->ec_stack.ga_len; tv1->v_type = VAR_BOOL; tv1->vval.v_number = res ? VVAL_TRUE : VVAL_FALSE; } break; \/\/ Operation with two number arguments case ISN_OPNR: case ISN_COMPARENR: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); varnumber_T arg1 = tv1->vval.v_number; varnumber_T arg2 = tv2->vval.v_number; varnumber_T res = 0; int div_zero = FALSE; switch (iptr->isn_arg.op.op_type) { case EXPR_MULT: res = arg1 * arg2; break; case EXPR_DIV: if (arg2 == 0) div_zero = TRUE; else res = arg1 \/ arg2; break; case EXPR_REM: if (arg2 == 0) div_zero = TRUE; else res = arg1 % arg2; break; case EXPR_SUB: res = arg1 - arg2; break; case EXPR_ADD: res = arg1 + arg2; break; case EXPR_EQUAL: res = arg1 == arg2; break; case EXPR_NEQUAL: res = arg1 != arg2; break; case EXPR_GREATER: res = arg1 > arg2; break; case EXPR_GEQUAL: res = arg1 >= arg2; break; case EXPR_SMALLER: res = arg1 < arg2; break; case EXPR_SEQUAL: res = arg1 <= arg2; break; default: break; } --ectx->ec_stack.ga_len; if (iptr->isn_type == ISN_COMPARENR) { tv1->v_type = VAR_BOOL; tv1->vval.v_number = res ? VVAL_TRUE : VVAL_FALSE; } else tv1->vval.v_number = res; if (div_zero) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_divide_by_zero)); goto on_error; } } break; \/\/ Computation with two float arguments case ISN_OPFLOAT: case ISN_COMPAREFLOAT: #ifdef FEAT_FLOAT { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); float_T arg1 = tv1->vval.v_float; float_T arg2 = tv2->vval.v_float; float_T res = 0; int cmp = FALSE; switch (iptr->isn_arg.op.op_type) { case EXPR_MULT: res = arg1 * arg2; break; case EXPR_DIV: res = arg1 \/ arg2; break; case EXPR_SUB: res = arg1 - arg2; break; case EXPR_ADD: res = arg1 + arg2; break; case EXPR_EQUAL: cmp = arg1 == arg2; break; case EXPR_NEQUAL: cmp = arg1 != arg2; break; case EXPR_GREATER: cmp = arg1 > arg2; break; case EXPR_GEQUAL: cmp = arg1 >= arg2; break; case EXPR_SMALLER: cmp = arg1 < arg2; break; case EXPR_SEQUAL: cmp = arg1 <= arg2; break; default: cmp = 0; break; } --ectx->ec_stack.ga_len; if (iptr->isn_type == ISN_COMPAREFLOAT) { tv1->v_type = VAR_BOOL; tv1->vval.v_number = cmp ? VVAL_TRUE : VVAL_FALSE; } else tv1->vval.v_float = res; } #endif break; case ISN_COMPARELIST: case ISN_COMPAREDICT: case ISN_COMPAREFUNC: case ISN_COMPARESTRING: case ISN_COMPAREBLOB: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); exprtype_T exprtype = iptr->isn_arg.op.op_type; int ic = iptr->isn_arg.op.op_ic; int res = FALSE; int status = OK; SOURCING_LNUM = iptr->isn_lnum; if (iptr->isn_type == ISN_COMPARELIST) { status = typval_compare_list(tv1, tv2, exprtype, ic, &res); } else if (iptr->isn_type == ISN_COMPAREDICT) { status = typval_compare_dict(tv1, tv2, exprtype, ic, &res); } else if (iptr->isn_type == ISN_COMPAREFUNC) { status = typval_compare_func(tv1, tv2, exprtype, ic, &res); } else if (iptr->isn_type == ISN_COMPARESTRING) { status = typval_compare_string(tv1, tv2, exprtype, ic, &res); } else { status = typval_compare_blob(tv1, tv2, exprtype, &res); } --ectx->ec_stack.ga_len; clear_tv(tv1); clear_tv(tv2); tv1->v_type = VAR_BOOL; tv1->vval.v_number = res ? VVAL_TRUE : VVAL_FALSE; if (status == FAIL) goto theend; } break; case ISN_COMPAREANY: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); exprtype_T exprtype = iptr->isn_arg.op.op_type; int ic = iptr->isn_arg.op.op_ic; int status; SOURCING_LNUM = iptr->isn_lnum; status = typval_compare(tv1, tv2, exprtype, ic); clear_tv(tv2); --ectx->ec_stack.ga_len; if (status == FAIL) goto theend; } break; case ISN_ADDLIST: case ISN_ADDBLOB: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); \/\/ add two lists or blobs if (iptr->isn_type == ISN_ADDLIST) { if (iptr->isn_arg.op.op_type == EXPR_APPEND && tv1->vval.v_list != NULL) list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL); else eval_addlist(tv1, tv2); } else eval_addblob(tv1, tv2); clear_tv(tv2); --ectx->ec_stack.ga_len; } break; case ISN_LISTAPPEND: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); list_T *l = tv1->vval.v_list; \/\/ add an item to a list SOURCING_LNUM = iptr->isn_lnum; if (l == NULL) { emsg(_(e_cannot_add_to_null_list)); goto on_error; } if (value_check_lock(l->lv_lock, NULL, FALSE)) goto on_error; if (list_append_tv(l, tv2) == FAIL) goto theend; clear_tv(tv2); --ectx->ec_stack.ga_len; } break; case ISN_BLOBAPPEND: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); blob_T *b = tv1->vval.v_blob; int error = FALSE; varnumber_T n; \/\/ add a number to a blob if (b == NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_cannot_add_to_null_blob)); goto on_error; } n = tv_get_number_chk(tv2, &error); if (error) goto on_error; ga_append(&b->bv_ga, (int)n); --ectx->ec_stack.ga_len; } break; \/\/ Computation with two arguments of unknown type case ISN_OPANY: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); varnumber_T n1, n2; #ifdef FEAT_FLOAT float_T f1 = 0, f2 = 0; #endif int error = FALSE; if (iptr->isn_arg.op.op_type == EXPR_ADD) { if (tv1->v_type == VAR_LIST && tv2->v_type == VAR_LIST) { eval_addlist(tv1, tv2); clear_tv(tv2); --ectx->ec_stack.ga_len; break; } else if (tv1->v_type == VAR_BLOB && tv2->v_type == VAR_BLOB) { eval_addblob(tv1, tv2); clear_tv(tv2); --ectx->ec_stack.ga_len; break; } } #ifdef FEAT_FLOAT if (tv1->v_type == VAR_FLOAT) { f1 = tv1->vval.v_float; n1 = 0; } else #endif { SOURCING_LNUM = iptr->isn_lnum; n1 = tv_get_number_chk(tv1, &error); if (error) goto on_error; #ifdef FEAT_FLOAT if (tv2->v_type == VAR_FLOAT) f1 = n1; #endif } #ifdef FEAT_FLOAT if (tv2->v_type == VAR_FLOAT) { f2 = tv2->vval.v_float; n2 = 0; } else #endif { n2 = tv_get_number_chk(tv2, &error); if (error) goto on_error; #ifdef FEAT_FLOAT if (tv1->v_type == VAR_FLOAT) f2 = n2; #endif } #ifdef FEAT_FLOAT \/\/ if there is a float on either side the result is a float if (tv1->v_type == VAR_FLOAT || tv2->v_type == VAR_FLOAT) { switch (iptr->isn_arg.op.op_type) { case EXPR_MULT: f1 = f1 * f2; break; case EXPR_DIV: f1 = f1 \/ f2; break; case EXPR_SUB: f1 = f1 - f2; break; case EXPR_ADD: f1 = f1 + f2; break; default: SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_cannot_use_percent_with_float)); goto on_error; } clear_tv(tv1); clear_tv(tv2); tv1->v_type = VAR_FLOAT; tv1->vval.v_float = f1; --ectx->ec_stack.ga_len; } else #endif { int failed = FALSE; switch (iptr->isn_arg.op.op_type) { case EXPR_MULT: n1 = n1 * n2; break; case EXPR_DIV: n1 = num_divide(n1, n2, &failed); if (failed) goto on_error; break; case EXPR_SUB: n1 = n1 - n2; break; case EXPR_ADD: n1 = n1 + n2; break; default: n1 = num_modulus(n1, n2, &failed); if (failed) goto on_error; break; } clear_tv(tv1); clear_tv(tv2); tv1->v_type = VAR_NUMBER; tv1->vval.v_number = n1; --ectx->ec_stack.ga_len; } } break; case ISN_CONCAT: { char_u *str1 = STACK_TV_BOT(-2)->vval.v_string; char_u *str2 = STACK_TV_BOT(-1)->vval.v_string; char_u *res; res = concat_str(str1, str2); clear_tv(STACK_TV_BOT(-2)); clear_tv(STACK_TV_BOT(-1)); --ectx->ec_stack.ga_len; STACK_TV_BOT(-1)->vval.v_string = res; } break; case ISN_STRINDEX: case ISN_STRSLICE: { int is_slice = iptr->isn_type == ISN_STRSLICE; varnumber_T n1 = 0, n2; char_u *res; \/\/ string index: string is at stack-2, index at stack-1 \/\/ string slice: string is at stack-3, first index at \/\/ stack-2, second index at stack-1 if (is_slice) { tv = STACK_TV_BOT(-2); n1 = tv->vval.v_number; } tv = STACK_TV_BOT(-1); n2 = tv->vval.v_number; ectx->ec_stack.ga_len -= is_slice ? 2 : 1; tv = STACK_TV_BOT(-1); if (is_slice) \/\/ Slice: Select the characters from the string res = string_slice(tv->vval.v_string, n1, n2, FALSE); else \/\/ Index: The resulting variable is a string of a \/\/ single character (including composing characters). \/\/ If the index is too big or negative the result is \/\/ empty. res = char_from_string(tv->vval.v_string, n2); vim_free(tv->vval.v_string); tv->vval.v_string = res; } break; case ISN_LISTINDEX: case ISN_LISTSLICE: case ISN_BLOBINDEX: case ISN_BLOBSLICE: { int is_slice = iptr->isn_type == ISN_LISTSLICE || iptr->isn_type == ISN_BLOBSLICE; int is_blob = iptr->isn_type == ISN_BLOBINDEX || iptr->isn_type == ISN_BLOBSLICE; varnumber_T n1, n2; typval_T *val_tv; \/\/ list index: list is at stack-2, index at stack-1 \/\/ list slice: list is at stack-3, indexes at stack-2 and \/\/ stack-1 \/\/ Same for blob. val_tv = is_slice ? STACK_TV_BOT(-3) : STACK_TV_BOT(-2); tv = STACK_TV_BOT(-1); n1 = n2 = tv->vval.v_number; clear_tv(tv); if (is_slice) { tv = STACK_TV_BOT(-2); n1 = tv->vval.v_number; clear_tv(tv); } ectx->ec_stack.ga_len -= is_slice ? 2 : 1; tv = STACK_TV_BOT(-1); SOURCING_LNUM = iptr->isn_lnum; if (is_blob) { if (blob_slice_or_index(val_tv->vval.v_blob, is_slice, n1, n2, FALSE, tv) == FAIL) goto on_error; } else { if (list_slice_or_index(val_tv->vval.v_list, is_slice, n1, n2, FALSE, tv, TRUE) == FAIL) goto on_error; } } break; case ISN_ANYINDEX: case ISN_ANYSLICE: { int is_slice = iptr->isn_type == ISN_ANYSLICE; typval_T *var1, *var2; int res; \/\/ index: composite is at stack-2, index at stack-1 \/\/ slice: composite is at stack-3, indexes at stack-2 and \/\/ stack-1 tv = is_slice ? STACK_TV_BOT(-3) : STACK_TV_BOT(-2); SOURCING_LNUM = iptr->isn_lnum; if (check_can_index(tv, TRUE, TRUE) == FAIL) goto on_error; var1 = is_slice ? STACK_TV_BOT(-2) : STACK_TV_BOT(-1); var2 = is_slice ? STACK_TV_BOT(-1) : NULL; res = eval_index_inner(tv, is_slice, var1, var2, FALSE, NULL, -1, TRUE); clear_tv(var1); if (is_slice) clear_tv(var2); ectx->ec_stack.ga_len -= is_slice ? 2 : 1; if (res == FAIL) goto on_error; } break; case ISN_SLICE: { list_T *list; int count = iptr->isn_arg.number; \/\/ type will have been checked to be a list tv = STACK_TV_BOT(-1); list = tv->vval.v_list; \/\/ no error for short list, expect it to be checked earlier if (list != NULL && list->lv_len >= count) { list_T *newlist = list_slice(list, count, list->lv_len - 1); if (newlist != NULL) { list_unref(list); tv->vval.v_list = newlist; ++newlist->lv_refcount; } } } break; case ISN_GETITEM: { listitem_T *li; getitem_T *gi = &iptr->isn_arg.getitem; \/\/ Get list item: list is at stack-1, push item. \/\/ List type and length is checked for when compiling. tv = STACK_TV_BOT(-1 - gi->gi_with_op); li = list_find(tv->vval.v_list, gi->gi_index); if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; ++ectx->ec_stack.ga_len; copy_tv(&li->li_tv, STACK_TV_BOT(-1)); \/\/ Useful when used in unpack assignment. Reset at \/\/ ISN_DROP. ectx->ec_where.wt_index = gi->gi_index + 1; ectx->ec_where.wt_variable = TRUE; } break; case ISN_MEMBER: { dict_T *dict; char_u *key; dictitem_T *di; \/\/ dict member: dict is at stack-2, key at stack-1 tv = STACK_TV_BOT(-2); \/\/ no need to check for VAR_DICT, CHECKTYPE will check. dict = tv->vval.v_dict; tv = STACK_TV_BOT(-1); \/\/ no need to check for VAR_STRING, 2STRING will check. key = tv->vval.v_string; if (key == NULL) key = (char_u *)\"\"; if ((di = dict_find(dict, key, -1)) == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_key_not_present_in_dictionary), key); \/\/ If :silent! is used we will continue, make sure the \/\/ stack contents makes sense and the dict stack is \/\/ updated. clear_tv(tv); --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(-1); (void) dict_stack_save(tv); tv->v_type = VAR_NUMBER; tv->vval.v_number = 0; goto on_fatal_error; } clear_tv(tv); --ectx->ec_stack.ga_len; \/\/ Put the dict used on the dict stack, it might be used by \/\/ a dict function later. tv = STACK_TV_BOT(-1); if (dict_stack_save(tv) == FAIL) goto on_fatal_error; copy_tv(&di->di_tv, tv); } break; \/\/ dict member with string key case ISN_STRINGMEMBER: { dict_T *dict; dictitem_T *di; tv = STACK_TV_BOT(-1); if (tv->v_type != VAR_DICT || tv->vval.v_dict == NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_dictionary_required)); goto on_error; } dict = tv->vval.v_dict; if ((di = dict_find(dict, iptr->isn_arg.string, -1)) == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_key_not_present_in_dictionary), iptr->isn_arg.string); goto on_error; } \/\/ Put the dict used on the dict stack, it might be used by \/\/ a dict function later. if (dict_stack_save(tv) == FAIL) goto on_fatal_error; copy_tv(&di->di_tv, tv); } break; case ISN_CLEARDICT: dict_stack_drop(); break; case ISN_USEDICT: { typval_T *dict_tv = dict_stack_get_tv(); \/\/ Turn \"dict.Func\" into a partial for \"Func\" bound to \/\/ \"dict\". Don't do this when \"Func\" is already a partial \/\/ that was bound explicitly (pt_auto is FALSE). tv = STACK_TV_BOT(-1); if (dict_tv != NULL && dict_tv->v_type == VAR_DICT && dict_tv->vval.v_dict != NULL && (tv->v_type == VAR_FUNC || (tv->v_type == VAR_PARTIAL && (tv->vval.v_partial->pt_auto || tv->vval.v_partial->pt_dict == NULL)))) dict_tv->vval.v_dict = make_partial(dict_tv->vval.v_dict, tv); dict_stack_drop(); } break; case ISN_NEGATENR: tv = STACK_TV_BOT(-1); if (tv->v_type != VAR_NUMBER #ifdef FEAT_FLOAT && tv->v_type != VAR_FLOAT #endif ) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_number_expected)); goto on_error; } #ifdef FEAT_FLOAT if (tv->v_type == VAR_FLOAT) tv->vval.v_float = -tv->vval.v_float; else #endif tv->vval.v_number = -tv->vval.v_number; break; case ISN_CHECKNR: { int error = FALSE; tv = STACK_TV_BOT(-1); SOURCING_LNUM = iptr->isn_lnum; if (check_not_string(tv) == FAIL) goto on_error; (void)tv_get_number_chk(tv, &error); if (error) goto on_error; } break; case ISN_CHECKTYPE: { checktype_T *ct = &iptr->isn_arg.type; tv = STACK_TV_BOT((int)ct->ct_off); SOURCING_LNUM = iptr->isn_lnum; if (!ectx->ec_where.wt_variable) ectx->ec_where.wt_index = ct->ct_arg_idx; if (check_typval_type(ct->ct_type, tv, ectx->ec_where) == FAIL) goto on_error; if (!ectx->ec_where.wt_variable) ectx->ec_where.wt_index = 0; \/\/ number 0 is FALSE, number 1 is TRUE if (tv->v_type == VAR_NUMBER && ct->ct_type->tt_type == VAR_BOOL && (tv->vval.v_number == 0 || tv->vval.v_number == 1)) { tv->v_type = VAR_BOOL; tv->vval.v_number = tv->vval.v_number ? VVAL_TRUE : VVAL_FALSE; } } break; case ISN_CHECKLEN: { int min_len = iptr->isn_arg.checklen.cl_min_len; list_T *list = NULL; tv = STACK_TV_BOT(-1); if (tv->v_type == VAR_LIST) list = tv->vval.v_list; if (list == NULL || list->lv_len < min_len || (list->lv_len > min_len && !iptr->isn_arg.checklen.cl_more_OK)) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_expected_nr_items_but_got_nr), min_len, list == NULL ? 0 : list->lv_len); goto on_error; } } break; case ISN_SETTYPE: { checktype_T *ct = &iptr->isn_arg.type; tv = STACK_TV_BOT(-1); if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL) { free_type(tv->vval.v_dict->dv_type); tv->vval.v_dict->dv_type = alloc_type(ct->ct_type); } else if (tv->v_type == VAR_LIST && tv->vval.v_list != NULL) { free_type(tv->vval.v_list->lv_type); tv->vval.v_list->lv_type = alloc_type(ct->ct_type); } } break; case ISN_2BOOL: case ISN_COND2BOOL: { int n; int error = FALSE; if (iptr->isn_type == ISN_2BOOL) { tv = STACK_TV_BOT(iptr->isn_arg.tobool.offset); n = tv2bool(tv); if (iptr->isn_arg.tobool.invert) n = !n; } else { tv = STACK_TV_BOT(-1); SOURCING_LNUM = iptr->isn_lnum; n = tv_get_bool_chk(tv, &error); if (error) goto on_error; } clear_tv(tv); tv->v_type = VAR_BOOL; tv->vval.v_number = n ? VVAL_TRUE : VVAL_FALSE; } break; case ISN_2STRING: case ISN_2STRING_ANY: SOURCING_LNUM = iptr->isn_lnum; if (do_2string(STACK_TV_BOT(iptr->isn_arg.tostring.offset), iptr->isn_type == ISN_2STRING_ANY, iptr->isn_arg.tostring.tolerant) == FAIL) goto on_error; break; case ISN_RANGE: { exarg_T ea; char *errormsg; ea.line2 = 0; ea.addr_count = 0; ea.addr_type = ADDR_LINES; ea.cmd = iptr->isn_arg.string; ea.skip = FALSE; if (parse_cmd_address(&ea, &errormsg, FALSE) == FAIL) goto on_error; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; ++ectx->ec_stack.ga_len; tv = STACK_TV_BOT(-1); tv->v_type = VAR_NUMBER; tv->v_lock = 0; if (ea.addr_count == 0) tv->vval.v_number = curwin->w_cursor.lnum; else tv->vval.v_number = ea.line2; } break; case ISN_PUT: { int regname = iptr->isn_arg.put.put_regname; linenr_T lnum = iptr->isn_arg.put.put_lnum; char_u *expr = NULL; int dir = FORWARD; if (lnum < -2) { \/\/ line number was put on the stack by ISN_RANGE tv = STACK_TV_BOT(-1); curwin->w_cursor.lnum = tv->vval.v_number; if (lnum == LNUM_VARIABLE_RANGE_ABOVE) dir = BACKWARD; --ectx->ec_stack.ga_len; } else if (lnum == -2) \/\/ :put! above cursor dir = BACKWARD; else if (lnum >= 0) curwin->w_cursor.lnum = iptr->isn_arg.put.put_lnum; if (regname == '=') { tv = STACK_TV_BOT(-1); if (tv->v_type == VAR_STRING) expr = tv->vval.v_string; else { expr = typval2string(tv, TRUE); \/\/ allocates value clear_tv(tv); } --ectx->ec_stack.ga_len; } check_cursor(); do_put(regname, expr, dir, 1L, PUT_LINE|PUT_CURSLINE); vim_free(expr); } break; case ISN_CMDMOD: ectx->ec_funclocal.floc_save_cmdmod = cmdmod; ectx->ec_funclocal.floc_restore_cmdmod = TRUE; ectx->ec_funclocal.floc_restore_cmdmod_stacklen = ectx->ec_stack.ga_len; cmdmod = *iptr->isn_arg.cmdmod.cf_cmdmod; apply_cmdmod(&cmdmod); break; case ISN_CMDMOD_REV: \/\/ filter regprog is owned by the instruction, don't free it cmdmod.cmod_filter_regmatch.regprog = NULL; undo_cmdmod(&cmdmod); cmdmod = ectx->ec_funclocal.floc_save_cmdmod; ectx->ec_funclocal.floc_restore_cmdmod = FALSE; break; case ISN_UNPACK: { int count = iptr->isn_arg.unpack.unp_count; int semicolon = iptr->isn_arg.unpack.unp_semicolon; list_T *l; listitem_T *li; int i; \/\/ Check there is a valid list to unpack. tv = STACK_TV_BOT(-1); if (tv->v_type != VAR_LIST) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_for_argument_must_be_sequence_of_lists)); goto on_error; } l = tv->vval.v_list; if (l == NULL || l->lv_len < (semicolon ? count - 1 : count)) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_list_value_does_not_have_enough_items)); goto on_error; } else if (!semicolon && l->lv_len > count) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_list_value_has_more_items_than_targets)); goto on_error; } CHECK_LIST_MATERIALIZE(l); if (GA_GROW_FAILS(&ectx->ec_stack, count - 1)) goto theend; ectx->ec_stack.ga_len += count - 1; \/\/ Variable after semicolon gets a list with the remaining \/\/ items. if (semicolon) { list_T *rem_list = list_alloc_with_items(l->lv_len - count + 1); if (rem_list == NULL) goto theend; tv = STACK_TV_BOT(-count); tv->vval.v_list = rem_list; ++rem_list->lv_refcount; tv->v_lock = 0; li = l->lv_first; for (i = 0; i < count - 1; ++i) li = li->li_next; for (i = 0; li != NULL; ++i) { list_set_item(rem_list, i, &li->li_tv); li = li->li_next; } --count; } \/\/ Produce the values in reverse order, first item last. li = l->lv_first; for (i = 0; i < count; ++i) { tv = STACK_TV_BOT(-i - 1); copy_tv(&li->li_tv, tv); li = li->li_next; } list_unref(l); } break; case ISN_PROF_START: case ISN_PROF_END: { #ifdef FEAT_PROFILE funccall_T cookie; ufunc_T *cur_ufunc = (((dfunc_T *)def_functions.ga_data) + ectx->ec_dfunc_idx)->df_ufunc; cookie.func = cur_ufunc; if (iptr->isn_type == ISN_PROF_START) { func_line_start(&cookie, iptr->isn_lnum); \/\/ if we get here the instruction is executed func_line_exec(&cookie); } else func_line_end(&cookie); #endif } break; case ISN_DEBUG: handle_debug(iptr, ectx); break; case ISN_SHUFFLE: { typval_T tmp_tv; int item = iptr->isn_arg.shuffle.shfl_item; int up = iptr->isn_arg.shuffle.shfl_up; tmp_tv = *STACK_TV_BOT(-item); for ( ; up > 0 && item > 1; --up) { *STACK_TV_BOT(-item) = *STACK_TV_BOT(-item + 1); --item; } *STACK_TV_BOT(-item) = tmp_tv; } break; case ISN_DROP: --ectx->ec_stack.ga_len; clear_tv(STACK_TV_BOT(0)); ectx->ec_where.wt_index = 0; ectx->ec_where.wt_variable = FALSE; break; } continue; func_return: \/\/ Restore previous function. If the frame pointer is where we started \/\/ then there is none and we are done. if (ectx->ec_frame_idx == ectx->ec_initial_frame_idx) goto done; if (func_return(ectx) == FAIL) \/\/ only fails when out of memory goto theend; continue; on_error: \/\/ Jump here for an error that does not require aborting execution. \/\/ If \"emsg_silent\" is set then ignore the error, unless it was set \/\/ when calling the function. if (did_emsg_cumul + did_emsg == ectx->ec_did_emsg_before && emsg_silent && did_emsg_def == 0) { \/\/ If a sequence of instructions causes an error while \":silent!\" \/\/ was used, restore the stack length and jump ahead to restoring \/\/ the cmdmod. if (ectx->ec_funclocal.floc_restore_cmdmod) { while (ectx->ec_stack.ga_len > ectx->ec_funclocal.floc_restore_cmdmod_stacklen) { --ectx->ec_stack.ga_len; clear_tv(STACK_TV_BOT(0)); } while (ectx->ec_instr[ectx->ec_iidx].isn_type != ISN_CMDMOD_REV) ++ectx->ec_iidx; } continue; } on_fatal_error: \/\/ Jump here for an error that messes up the stack. \/\/ If we are not inside a try-catch started here, abort execution. if (trylevel <= ectx->ec_trylevel_at_start) goto theend; } done: ret = OK; theend: dict_stack_clear(dict_stack_len_at_start); ectx->ec_trylevel_at_start = save_trylevel_at_start; return ret; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":71900,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { char s[2]; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MaxTextExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MaxTextExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; \/* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; *\/ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; property=(const char *) NULL; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->magick= %s\",image_info->magick); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register PixelPacket *r; ExceptionInfo *exception; exception=(&image->exception); if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->matte == MagickFalse))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ number_opaque = (int) image->colors; if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; else ping_have_color=MagickTrue; ping_have_non_bw=MagickFalse; if (image->matte != MagickFalse) { number_transparent = 2; number_semitransparent = 1; } else { number_transparent = 0; number_semitransparent = 0; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->matte is MagickFalse, we ignore the opacity channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ ExceptionInfo *exception; int n; PixelPacket opaque[260], semitransparent[260], transparent[260]; register IndexPacket *indexes; register const PixelPacket *s, *q; register PixelPacket *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->matte=%.20g\",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,opacity)\"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } exception=(&image->exception); image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte == MagickFalse || GetPixelOpacity(q) == OpaqueOpacity) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelRGB(q, opaque); opaque[0].opacity=OpaqueOpacity; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(q, opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelRGB(q, opaque+i); opaque[i].opacity=OpaqueOpacity; } } } else if (q->opacity == TransparentOpacity) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelRGBO(q, transparent); ping_trans_color.red= (unsigned short) GetPixelRed(q); ping_trans_color.green= (unsigned short) GetPixelGreen(q); ping_trans_color.blue= (unsigned short) GetPixelBlue(q); ping_trans_color.gray= (unsigned short) GetPixelRed(q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(q, transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelRGBO(q, transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelRGBO(q, semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(q, semitransparent+i) && GetPixelOpacity(q) == semitransparent[i].opacity) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelRGBO(q, semitransparent+i); } } } q++; } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != GetPixelGreen(s) || GetPixelRed(s) != GetPixelBlue(s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s++; } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != 0 && GetPixelRed(s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s++; } } } } } if (image_colors < 257) { PixelPacket colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->matte == MagickFalse || image->colormap[i].opacity == GetPixelOpacity(q)) && image->colormap[i].red == GetPixelRed(q) && image->colormap[i].green == GetPixelGreen(q) && image->colormap[i].blue == GetPixelBlue(q)) { SetPixelIndex(indexes+x,i); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,opacity)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) > TransparentOpacity\/2) { SetPixelOpacity(r,TransparentOpacity); SetPixelRgb(r,&image->background_color); } else SetPixelOpacity(r,OpaqueOpacity); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].opacity = (image->colormap[i].opacity > TransparentOpacity\/2 ? TransparentOpacity : OpaqueOpacity); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR04PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR03PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR02PixelBlue(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 && GetPixelOpacity(r) == OpaqueOpacity) { SetPixelRed(r,ScaleCharToQuantum(0x24)); } r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { ExceptionInfo *exception; register const PixelPacket *q; exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (q->opacity != TransparentOpacity && (unsigned short) GetPixelRed(q) == ping_trans_color.red && (unsigned short) GetPixelGreen(q) == ping_trans_color.green && (unsigned short) GetPixelBlue(q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q++; } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->matte; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",image->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->x_resolution != 0) && (image->y_resolution != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->x_resolution+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->y_resolution+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->x_resolution; ping_pHYs_y_resolution=(png_uint_32) image->y_resolution; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorMatteType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteMatteType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, image->colormap))) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) (255- ScaleQuantumToChar(image->colormap[i].opacity)); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)*(ScaleQuantumToShort((Quantum) GetPixelLuma(image,&image->background_color)))+.5); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_background.index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_background.gray is %d\", (int) ping_background.gray); } ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This is addressed by using \"-define png:compression-strategy\", etc., which takes precedence over -quality. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->matte == MagickFalse) { \/* Add an opaque matte channel *\/ image->matte = MagickTrue; (void) SetImageOpacity(image,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { if (mng_info->have_write_global_plte && matte == MagickFalse) { png_set_PLTE(ping,ping_info,NULL,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up empty PLTE chunk\"); } else png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(const png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } else #endif { if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } if (ping_exclude_zCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXT chunk with uuencoded ICC\"); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk with %s profile\",name); name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\"); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; (void) ping_have_blob; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { \/* Palette, Bilevel, or Opaque Monochrome *\/ register const PixelPacket *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { \/* Undo pixel scaling *\/ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\",pass); p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(image,\"png:bit-depth-written\",s); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":474596,"input":"deliver_message(uschar *id, BOOL forced, BOOL give_up) { int i, rc; int final_yield = DELIVER_ATTEMPTED_NORMAL; time_t now = time(NULL); address_item *addr_last = NULL; uschar *filter_message = NULL; int process_recipients = RECIP_ACCEPT; open_db dbblock; open_db *dbm_file; extern int acl_where; uschar *info = queue_run_pid == (pid_t)0 ? string_sprintf(\"delivering %s\", id) : string_sprintf(\"delivering %s (queue run pid %d)\", id, queue_run_pid); \/* If the D_process_info bit is on, set_process_info() will output debugging information. If not, we want to show this initial information if D_deliver or D_queue_run is set or in verbose mode. *\/ set_process_info(\"%s\", info); if ( !(debug_selector & D_process_info) && (debug_selector & (D_deliver|D_queue_run|D_v)) ) debug_printf(\"%s\\n\", info); \/* Ensure that we catch any subprocesses that are created. Although Exim sets SIG_DFL as its initial default, some routes through the code end up here with it set to SIG_IGN - cases where a non-synchronous delivery process has been forked, but no re-exec has been done. We use sigaction rather than plain signal() on those OS where SA_NOCLDWAIT exists, because we want to be sure it is turned off. (There was a problem on AIX with this.) *\/ #ifdef SA_NOCLDWAIT { struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(SIGCHLD, &act, NULL); } #else signal(SIGCHLD, SIG_DFL); #endif \/* Make the forcing flag available for routers and transports, set up the global message id field, and initialize the count for returned files and the message size. This use of strcpy() is OK because the length id is checked when it is obtained from a command line (the -M or -q options), and otherwise it is known to be a valid message id. *\/ Ustrcpy(message_id, id); f.deliver_force = forced; return_count = 0; message_size = 0; \/* Initialize some flags *\/ update_spool = FALSE; remove_journal = TRUE; \/* Set a known context for any ACLs we call via expansions *\/ acl_where = ACL_WHERE_DELIVERY; \/* Reset the random number generator, so that if several delivery processes are started from a queue runner that has already used random numbers (for sorting), they don't all get the same sequence. *\/ random_seed = 0; \/* Open and lock the message's data file. Exim locks on this one because the header file may get replaced as it is re-written during the delivery process. Any failures cause messages to be written to the log, except for missing files while queue running - another process probably completed delivery. As part of opening the data file, message_subdir gets set. *\/ if ((deliver_datafile = spool_open_datafile(id)) < 0) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ \/* The value of message_size at this point has been set to the data length, plus one for the blank line that notionally precedes the data. *\/ \/* Now read the contents of the header file, which will set up the headers in store, and also the list of recipients and the tree of non-recipients and assorted flags. It updates message_size. If there is a reading or format error, give up; if the message has been around for sufficiently long, remove it. *\/ { uschar * spoolname = string_sprintf(\"%s-H\", id); if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK) { if (errno == ERRNO_SPOOLFORMAT) { struct stat statbuf; if (Ustat(spool_fname(US\"input\", message_subdir, spoolname, US\"\"), &statbuf) == 0) log_write(0, LOG_MAIN, \"Format error in spool file %s: \" \"size=\" OFF_T_FMT, spoolname, statbuf.st_size); else log_write(0, LOG_MAIN, \"Format error in spool file %s\", spoolname); } else log_write(0, LOG_MAIN, \"Error reading spool file %s: %s\", spoolname, strerror(errno)); \/* If we managed to read the envelope data, received_time contains the time the message was received. Otherwise, we can calculate it from the message id. *\/ if (rc != spool_read_hdrerror) { received_time.tv_sec = received_time.tv_usec = 0; \/*XXX subsec precision?*\/ for (i = 0; i < 6; i++) received_time.tv_sec = received_time.tv_sec * BASE_62 + tab62[id[i] - '0']; } \/* If we've had this malformed message too long, sling it. *\/ if (now - received_time.tv_sec > keep_malformed) { Uunlink(spool_fname(US\"msglog\", message_subdir, id, US\"\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-H\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-J\")); log_write(0, LOG_MAIN, \"Message removed because older than %s\", readconf_printtime(keep_malformed)); } (void)close(deliver_datafile); deliver_datafile = -1; return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* The spool header file has been read. Look to see if there is an existing journal file for this message. If there is, it means that a previous delivery attempt crashed (program or host) before it could update the spool header file. Read the list of delivered addresses from the journal and add them to the nonrecipients tree. Then update the spool file. We can leave the journal in existence, as it will get further successful deliveries added to it in this run, and it will be deleted if this function gets to its end successfully. Otherwise it might be needed again. *\/ { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); FILE * jread; if ( (journal_fd = Uopen(fname, O_RDWR|O_APPEND #ifdef O_CLOEXEC | O_CLOEXEC #endif #ifdef O_NOFOLLOW | O_NOFOLLOW #endif , SPOOL_MODE)) >= 0 && lseek(journal_fd, 0, SEEK_SET) == 0 && (jread = fdopen(journal_fd, \"rb\")) ) { while (Ufgets(big_buffer, big_buffer_size, jread)) { int n = Ustrlen(big_buffer); big_buffer[n-1] = 0; tree_add_nonrecipient(big_buffer); DEBUG(D_deliver) debug_printf(\"Previously delivered address %s taken from \" \"journal file\\n\", big_buffer); } rewind(jread); if ((journal_fd = dup(fileno(jread))) < 0) journal_fd = fileno(jread); else (void) fclose(jread); \/* Try to not leak the FILE resource *\/ \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } else if (errno != ENOENT) { log_write(0, LOG_MAIN|LOG_PANIC, \"attempt to open journal for reading gave: \" \"%s\", strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* A null recipients list indicates some kind of disaster. *\/ if (!recipients_list) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN, \"Spool error: no recipients for %s\", fname); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* Handle a message that is frozen. There are a number of different things that can happen, but in the default situation, unless forced, no delivery is attempted. *\/ if (f.deliver_freeze) { #ifdef SUPPORT_MOVE_FROZEN_MESSAGES \/* Moving to another directory removes the message from Exim's view. Other tools must be used to deal with it. Logging of this action happens in spool_move_message() and its subfunctions. *\/ if ( move_frozen_messages && spool_move_message(id, message_subdir, US\"\", US\"F\") ) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ #endif \/* For all frozen messages (bounces or not), timeout_frozen_after sets the maximum time to keep messages that are frozen. Thaw if we reach it, with a flag causing all recipients to be failed. The time is the age of the message, not the time since freezing. *\/ if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after) { log_write(0, LOG_MAIN, \"cancelled by timeout_frozen_after\"); process_recipients = RECIP_FAIL_TIMEOUT; } \/* For bounce messages (and others with no sender), thaw if the error message ignore timer is exceeded. The message will be discarded if this delivery fails. *\/ else if (!*sender_address && message_age >= ignore_bounce_errors_after) log_write(0, LOG_MAIN, \"Unfrozen by errmsg timer\"); \/* If this is a bounce message, or there's no auto thaw, or we haven't reached the auto thaw time yet, and this delivery is not forced by an admin user, do not attempt delivery of this message. Note that forced is set for continuing messages down the same channel, in order to skip load checking and ignore hold domains, but we don't want unfreezing in that case. *\/ else { if ( ( sender_address[0] == 0 || auto_thaw <= 0 || now <= deliver_frozen_at + auto_thaw ) && ( !forced || !f.deliver_force_thaw || !f.admin_user || continue_hostname ) ) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(L_skip_delivery, LOG_MAIN, \"Message is frozen\"); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* If delivery was forced (by an admin user), assume a manual thaw. Otherwise it's an auto thaw. *\/ if (forced) { f.deliver_manual_thaw = TRUE; log_write(0, LOG_MAIN, \"Unfrozen by forced delivery\"); } else log_write(0, LOG_MAIN, \"Unfrozen by auto-thaw\"); } \/* We get here if any of the rules for unfreezing have triggered. *\/ f.deliver_freeze = FALSE; update_spool = TRUE; } \/* Open the message log file if we are using them. This records details of deliveries, deferments, and failures for the benefit of the mail administrator. The log is not used by exim itself to track the progress of a message; that is done by rewriting the header spool file. *\/ if (message_logs) { uschar * fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); uschar * error; int fd; if ((fd = open_msglog_file(fname, SPOOL_MODE, &error)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't %s message log %s: %s\", error, fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Make a C stream out of it. *\/ if (!(message_log = fdopen(fd, \"a\"))) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't fdopen message log %s: %s\", fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* If asked to give up on a message, log who did it, and set the action for all the addresses. *\/ if (give_up) { struct passwd *pw = getpwuid(real_uid); log_write(0, LOG_MAIN, \"cancelled by %s\", pw ? US pw->pw_name : string_sprintf(\"uid %ld\", (long int)real_uid)); process_recipients = RECIP_FAIL; } \/* Otherwise, if there are too many Received: headers, fail all recipients. *\/ else if (received_count > received_headers_max) process_recipients = RECIP_FAIL_LOOP; \/* Otherwise, if a system-wide, address-independent message filter is specified, run it now, except in the case when we are failing all recipients as a result of timeout_frozen_after. If the system filter yields \"delivered\", then ignore the true recipients of the message. Failure of the filter file is logged, and the delivery attempt fails. *\/ else if (system_filter && process_recipients != RECIP_FAIL_TIMEOUT) { int rc; int filtertype; ugid_block ugid; redirect_block redirect; if (system_filter_uid_set) { ugid.uid = system_filter_uid; ugid.gid = system_filter_gid; ugid.uid_set = ugid.gid_set = TRUE; } else { ugid.uid_set = ugid.gid_set = FALSE; } return_path = sender_address; f.enable_dollar_recipients = TRUE; \/* Permit $recipients in system filter *\/ f.system_filtering = TRUE; \/* Any error in the filter file causes a delivery to be abandoned. *\/ redirect.string = system_filter; redirect.isfile = TRUE; redirect.check_owner = redirect.check_group = FALSE; redirect.owners = NULL; redirect.owngroups = NULL; redirect.pw = NULL; redirect.modemask = 0; DEBUG(D_deliver|D_filter) debug_printf(\"running system filter\\n\"); rc = rda_interpret( &redirect, \/* Where the data is *\/ RDO_DEFER | \/* Turn on all the enabling options *\/ RDO_FAIL | \/* Leave off all the disabling options *\/ RDO_FILTER | RDO_FREEZE | RDO_REALLOG | RDO_REWRITE, NULL, \/* No :include: restriction (not used in filter) *\/ NULL, \/* No sieve vacation directory (not sieve!) *\/ NULL, \/* No sieve enotify mailto owner (not sieve!) *\/ NULL, \/* No sieve user address (not sieve!) *\/ NULL, \/* No sieve subaddress (not sieve!) *\/ &ugid, \/* uid\/gid data *\/ &addr_new, \/* Where to hang generated addresses *\/ &filter_message, \/* Where to put error message *\/ NULL, \/* Don't skip syntax errors *\/ &filtertype, \/* Will always be set to FILTER_EXIM for this call *\/ US\"system filter\"); \/* For error messages *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter returned %d\\n\", rc); if (rc == FF_ERROR || rc == FF_NONEXIST) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN|LOG_PANIC, \"Error in system filter: %s\", string_printing(filter_message)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Reset things. If the filter message is an empty string, which can happen for a filter \"fail\" or \"freeze\" command with no text, reset it to NULL. *\/ f.system_filtering = FALSE; f.enable_dollar_recipients = FALSE; if (filter_message && filter_message[0] == 0) filter_message = NULL; \/* Save the values of the system filter variables so that user filters can use them. *\/ memcpy(filter_sn, filter_n, sizeof(filter_sn)); \/* The filter can request that delivery of the original addresses be deferred. *\/ if (rc == FF_DEFER) { process_recipients = RECIP_DEFER; deliver_msglog(\"Delivery deferred by system filter\\n\"); log_write(0, LOG_MAIN, \"Delivery deferred by system filter\"); } \/* The filter can request that a message be frozen, but this does not take place if the message has been manually thawed. In that case, we must unset \"delivered\", which is forced by the \"freeze\" command to make -bF work properly. *\/ else if (rc == FF_FREEZE && !f.deliver_manual_thaw) { f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); process_recipients = RECIP_DEFER; frozen_info = string_sprintf(\" by the system filter%s%s\", filter_message ? US\": \" : US\"\", filter_message ? filter_message : US\"\"); } \/* The filter can request that a message be failed. The error message may be quite long - it is sent back to the sender in the bounce - but we don't want to fill up the log with repetitions of it. If it starts with << then the text between << and >> is written to the log, with the rest left for the bounce message. *\/ else if (rc == FF_FAIL) { uschar *colon = US\"\"; uschar *logmsg = US\"\"; int loglen = 0; process_recipients = RECIP_FAIL_FILTER; if (filter_message) { uschar *logend; colon = US\": \"; if ( filter_message[0] == '<' && filter_message[1] == '<' && (logend = Ustrstr(filter_message, \">>\")) ) { logmsg = filter_message + 2; loglen = logend - logmsg; filter_message = logend + 2; if (filter_message[0] == 0) filter_message = NULL; } else { logmsg = filter_message; loglen = Ustrlen(filter_message); } } log_write(0, LOG_MAIN, \"cancelled by system filter%s%.*s\", colon, loglen, logmsg); } \/* Delivery can be restricted only to those recipients (if any) that the filter specified. *\/ else if (rc == FF_DELIVERED) { process_recipients = RECIP_IGNORE; if (addr_new) log_write(0, LOG_MAIN, \"original recipients ignored (system filter)\"); else log_write(0, LOG_MAIN, \"=> discarded (system filter)\"); } \/* If any new addresses were created by the filter, fake up a \"parent\" for them. This is necessary for pipes, etc., which are expected to have parents, and it also gives some sensible logging for others. Allow pipes, files, and autoreplies, and run them as the filter uid if set, otherwise as the current uid. *\/ if (addr_new) { int uid = (system_filter_uid_set)? system_filter_uid : geteuid(); int gid = (system_filter_gid_set)? system_filter_gid : getegid(); \/* The text \"system-filter\" is tested in transport_set_up_command() and in set_up_shell_command() in the pipe transport, to enable them to permit $recipients, so don't change it here without also changing it there. *\/ address_item *p = addr_new; address_item *parent = deliver_make_addr(US\"system-filter\", FALSE); parent->domain = string_copylc(qualify_domain_recipient); parent->local_part = US\"system-filter\"; \/* As part of this loop, we arrange for addr_last to end up pointing at the final address. This is used if we go on to add addresses for the original recipients. *\/ while (p) { if (parent->child_count == USHRT_MAX) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"system filter generated more \" \"than %d delivery addresses\", USHRT_MAX); parent->child_count++; p->parent = parent; if (testflag(p, af_pfr)) { uschar *tpname; uschar *type; p->uid = uid; p->gid = gid; setflag(p, af_uid_set); setflag(p, af_gid_set); setflag(p, af_allow_file); setflag(p, af_allow_pipe); setflag(p, af_allow_reply); \/* Find the name of the system filter's appropriate pfr transport *\/ if (p->address[0] == '|') { type = US\"pipe\"; tpname = system_filter_pipe_transport; address_pipe = p->address; } else if (p->address[0] == '>') { type = US\"reply\"; tpname = system_filter_reply_transport; } else { if (p->address[Ustrlen(p->address)-1] == '\/') { type = US\"directory\"; tpname = system_filter_directory_transport; } else { type = US\"file\"; tpname = system_filter_file_transport; } address_file = p->address; } \/* Now find the actual transport, first expanding the name. We have set address_file or address_pipe above. *\/ if (tpname) { uschar *tmp = expand_string(tpname); address_file = address_pipe = NULL; if (!tmp) p->message = string_sprintf(\"failed to expand \\\"%s\\\" as a \" \"system filter transport name\", tpname); tpname = tmp; } else p->message = string_sprintf(\"system_filter_%s_transport is unset\", type); if (tpname) { transport_instance *tp; for (tp = transports; tp; tp = tp->next) if (Ustrcmp(tp->name, tpname) == 0) { p->transport = tp; break; } if (!tp) p->message = string_sprintf(\"failed to find \\\"%s\\\" transport \" \"for system filter delivery\", tpname); } \/* If we couldn't set up a transport, defer the delivery, putting the error on the panic log as well as the main log. *\/ if (!p->transport) { address_item *badp = p; p = p->next; if (!addr_last) addr_new = p; else addr_last->next = p; badp->local_part = badp->address; \/* Needed for log line *\/ post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, EXIM_DTYPE_ROUTER, 0); continue; } } \/* End of pfr handling *\/ \/* Either a non-pfr delivery, or we found a transport *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter added %s\\n\", p->address); addr_last = p; p = p->next; } \/* Loop through all addr_new addresses *\/ } } \/* Scan the recipients list, and for every one that is not in the non- recipients tree, add an addr item to the chain of new addresses. If the pno value is non-negative, we must set the onetime parent from it. This which points to the relevant entry in the recipients list. This processing can be altered by the setting of the process_recipients variable, which is changed if recipients are to be ignored, failed, or deferred. This can happen as a result of system filter activity, or if the -Mg option is used to fail all of them. Duplicate addresses are handled later by a different tree structure; we can't just extend the non-recipients tree, because that will be re-written to the spool if the message is deferred, and in any case there are casing complications for local addresses. *\/ if (process_recipients != RECIP_IGNORE) for (i = 0; i < recipients_count; i++) if (!tree_search(tree_nonrecipients, recipients_list[i].address)) { recipient_item *r = recipients_list + i; address_item *new = deliver_make_addr(r->address, FALSE); new->prop.errors_address = r->errors_to; #ifdef SUPPORT_I18N if ((new->prop.utf8_msg = message_smtputf8)) { new->prop.utf8_downcvt = message_utf8_downconvert == 1; new->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1; DEBUG(D_deliver) debug_printf(\"utf8, downconvert %s\\n\", new->prop.utf8_downcvt ? \"yes\" : new->prop.utf8_downcvt_maybe ? \"ifneeded\" : \"no\"); } #endif if (r->pno >= 0) new->onetime_parent = recipients_list[r->pno].address; \/* If DSN support is enabled, set the dsn flags and the original receipt to be passed on to other DSN enabled MTAs *\/ new->dsn_flags = r->dsn_flags & rf_dsnflags; new->dsn_orcpt = r->orcpt; DEBUG(D_deliver) debug_printf(\"DSN: set orcpt: %s flags: %d\\n\", new->dsn_orcpt ? new->dsn_orcpt : US\"\", new->dsn_flags); switch (process_recipients) { \/* RECIP_DEFER is set when a system filter freezes a message. *\/ case RECIP_DEFER: new->next = addr_defer; addr_defer = new; break; \/* RECIP_FAIL_FILTER is set when a system filter has obeyed a \"fail\" command. *\/ case RECIP_FAIL_FILTER: new->message = filter_message ? filter_message : US\"delivery cancelled\"; setflag(new, af_pass_message); goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older than the value in timeout_frozen_after. Treat non-bounce messages similarly to -Mg; for bounce messages we just want to discard, so don't put the address on the failed list. The timeout has already been logged. *\/ case RECIP_FAIL_TIMEOUT: new->message = US\"delivery cancelled; message timed out\"; goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL is set when -Mg has been used. *\/ case RECIP_FAIL: new->message = US\"delivery cancelled by administrator\"; \/* Fall through *\/ \/* Common code for the failure cases above. If this is not a bounce message, put the address on the failed list so that it is used to create a bounce. Otherwise do nothing - this just discards the address. The incident has already been logged. *\/ RECIP_QUEUE_FAILED: if (sender_address[0]) { new->next = addr_failed; addr_failed = new; } break; \/* RECIP_FAIL_LOOP is set when there are too many Received: headers in the message. Process each address as a routing failure; if this is a bounce message, it will get frozen. *\/ case RECIP_FAIL_LOOP: new->message = US\"Too many \\\"Received\\\" headers - suspected mail loop\"; post_process_one(new, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); break; \/* Value should be RECIP_ACCEPT; take this as the safe default. *\/ default: if (!addr_new) addr_new = new; else addr_last->next = new; addr_last = new; break; } #ifndef DISABLE_EVENT if (process_recipients != RECIP_ACCEPT) { uschar * save_local = deliver_localpart; const uschar * save_domain = deliver_domain; uschar * addr = new->address, * errmsg = NULL; int start, end, dom; if (!parse_extract_address(addr, &errmsg, &start, &end, &dom, TRUE)) log_write(0, LOG_MAIN|LOG_PANIC, \"failed to parse address '%.100s': %s\\n\", addr, errmsg); else { deliver_localpart = string_copyn(addr+start, dom ? (dom-1) - start : end - start); deliver_domain = dom ? CUS string_copyn(addr+dom, end - dom) : CUS\"\"; event_raise(event_action, US\"msg:fail:internal\", new->message); deliver_localpart = save_local; deliver_domain = save_domain; } } #endif } DEBUG(D_deliver) { address_item *p; debug_printf(\"Delivery address list:\\n\"); for (p = addr_new; p; p = p->next) debug_printf(\" %s %s\\n\", p->address, p->onetime_parent ? p->onetime_parent : US\"\"); } \/* Set up the buffers used for copying over the file when delivering. *\/ deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE); deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE); \/* Until there are no more new addresses, handle each one as follows: . If this is a generated address (indicated by the presence of a parent pointer) then check to see whether it is a pipe, file, or autoreply, and if so, handle it directly here. The router that produced the address will have set the allow flags into the address, and also set the uid\/gid required. Having the routers generate new addresses and then checking them here at the outer level is tidier than making each router do the checking, and means that routers don't need access to the failed address queue. . Break up the address into local part and domain, and make lowercased versions of these strings. We also make unquoted versions of the local part. . Handle the percent hack for those domains for which it is valid. . For child addresses, determine if any of the parents have the same address. If so, generate a different string for previous delivery checking. Without this code, if the address spqr generates spqr via a forward or alias file, delivery of the generated spqr stops further attempts at the top level spqr, which is not what is wanted - it may have generated other addresses. . Check on the retry database to see if routing was previously deferred, but only if in a queue run. Addresses that are to be routed are put on the addr_route chain. Addresses that are to be deferred are put on the addr_defer chain. We do all the checking first, so as not to keep the retry database open any longer than necessary. . Now we run the addresses through the routers. A router may put the address on either the addr_local or the addr_remote chain for local or remote delivery, respectively, or put it on the addr_failed chain if it is undeliveable, or it may generate child addresses and put them on the addr_new chain, or it may defer an address. All the chain anchors are passed as arguments so that the routers can be called for verification purposes as well. . If new addresses have been generated by the routers, da capo. *\/ f.header_rewritten = FALSE; \/* No headers rewritten yet *\/ while (addr_new) \/* Loop until all addresses dealt with *\/ { address_item *addr, *parent; \/* Failure to open the retry database is treated the same as if it does not exist. In both cases, dbm_file is NULL. *\/ if (!(dbm_file = dbfn_open(US\"retry\", O_RDONLY, &dbblock, FALSE))) DEBUG(D_deliver|D_retry|D_route|D_hints_lookup) debug_printf(\"no retry data available\\n\"); \/* Scan the current batch of new addresses, to handle pipes, files and autoreplies, and determine which others are ready for routing. *\/ while (addr_new) { int rc; uschar *p; tree_node *tnode; dbdata_retry *domain_retry_record; dbdata_retry *address_retry_record; addr = addr_new; addr_new = addr->next; DEBUG(D_deliver|D_retry|D_route) { debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"Considering: %s\\n\", addr->address); } \/* Handle generated address that is a pipe or a file or an autoreply. *\/ if (testflag(addr, af_pfr)) { \/* If an autoreply in a filter could not generate a syntactically valid address, give up forthwith. Set af_ignore_error so that we don't try to generate a bounce. *\/ if (testflag(addr, af_bad_reply)) { addr->basic_errno = ERRNO_BADADDRESS2; addr->local_part = addr->address; addr->message = US\"filter autoreply generated syntactically invalid recipient\"; addr->prop.ignore_error = TRUE; (void) post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If two different users specify delivery to the same pipe or file or autoreply, there should be two different deliveries, so build a unique string that incorporates the original address, and use this for duplicate testing and recording delivery, and also for retrying. *\/ addr->unique = string_sprintf(\"%s:%s\", addr->address, addr->parent->unique + (testflag(addr->parent, af_homonym)? 3:0)); addr->address_retry_key = addr->domain_retry_key = string_sprintf(\"T:%s\", addr->unique); \/* If a filter file specifies two deliveries to the same pipe or file, we want to de-duplicate, but this is probably not wanted for two mail commands to the same address, where probably both should be delivered. So, we have to invent a different unique string in that case. Just keep piling '>' characters on the front. *\/ if (addr->address[0] == '>') { while (tree_search(tree_duplicates, addr->unique)) addr->unique = string_sprintf(\">%s\", addr->unique); } else if ((tnode = tree_search(tree_duplicates, addr->unique))) { DEBUG(D_deliver|D_route) debug_printf(\"%s is a duplicate address: discarded\\n\", addr->address); addr->dupof = tnode->data.ptr; addr->next = addr_duplicate; addr_duplicate = addr; continue; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); \/* Check for previous delivery *\/ if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->address); child_done(addr, tod_stamp(tod_log)); continue; } \/* Save for checking future duplicates *\/ tree_add_duplicate(addr->unique, addr); \/* Set local part and domain *\/ addr->local_part = addr->address; addr->domain = addr->parent->domain; \/* Ensure that the delivery is permitted. *\/ if (testflag(addr, af_file)) { if (!testflag(addr, af_allow_file)) { addr->basic_errno = ERRNO_FORBIDFILE; addr->message = US\"delivery to file forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (addr->address[0] == '|') { if (!testflag(addr, af_allow_pipe)) { addr->basic_errno = ERRNO_FORBIDPIPE; addr->message = US\"delivery to pipe forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (!testflag(addr, af_allow_reply)) { addr->basic_errno = ERRNO_FORBIDREPLY; addr->message = US\"autoreply forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If the errno field is already set to BADTRANSPORT, it indicates failure to expand a transport string, or find the associated transport, or an unset transport when one is required. Leave this test till now so that the forbid errors are given in preference. *\/ if (addr->basic_errno == ERRNO_BADTRANSPORT) { (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; } \/* Treat \/dev\/null as a special case and abandon the delivery. This avoids having to specify a uid on the transport just for this case. Arrange for the transport name to be logged as \"**bypassed**\". *\/ if (Ustrcmp(addr->address, \"\/dev\/null\") == 0) { uschar *save = addr->transport->name; addr->transport->name = US\"**bypassed**\"; (void)post_process_one(addr, OK, LOG_MAIN, EXIM_DTYPE_TRANSPORT, '='); addr->transport->name = save; continue; \/* with the next new address *\/ } \/* Pipe, file, or autoreply delivery is to go ahead as a normal local delivery. *\/ DEBUG(D_deliver|D_route) debug_printf(\"queued for %s transport\\n\", addr->transport->name); addr->next = addr_local; addr_local = addr; continue; \/* with the next new address *\/ } \/* Handle normal addresses. First, split up into local part and domain, handling the %-hack if necessary. There is the possibility of a defer from a lookup in percent_hack_domains. *\/ if ((rc = deliver_split_address(addr)) == DEFER) { addr->message = US\"cannot check percent_hack_domains\"; addr->basic_errno = ERRNO_LISTDEFER; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Check to see if the domain is held. If so, proceed only if the delivery was forced by hand. *\/ deliver_domain = addr->domain; \/* set $domain *\/ if ( !forced && hold_domains && (rc = match_isinlist(addr->domain, (const uschar **)&hold_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != FAIL ) { if (rc == DEFER) { addr->message = US\"hold_domains lookup deferred\"; addr->basic_errno = ERRNO_LISTDEFER; } else { addr->message = US\"domain is held\"; addr->basic_errno = ERRNO_HELD; } (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Now we can check for duplicates and previously delivered addresses. In order to do this, we have to generate a \"unique\" value for each address, because there may be identical actual addresses in a line of descendents. The \"unique\" field is initialized to the same value as the \"address\" field, but gets changed here to cope with identically-named descendents. *\/ for (parent = addr->parent; parent; parent = parent->parent) if (strcmpic(addr->address, parent->address) == 0) break; \/* If there's an ancestor with the same name, set the homonym flag. This influences how deliveries are recorded. Then add a prefix on the front of the unique address. We use \\n\\ where n starts at 0 and increases each time. It is unlikely to pass 9, but if it does, it may look odd but will still work. This means that siblings or cousins with the same names are treated as duplicates, which is what we want. *\/ if (parent) { setflag(addr, af_homonym); if (parent->unique[0] != '\\\\') addr->unique = string_sprintf(\"\\\\0\\\\%s\", addr->address); else addr->unique = string_sprintf(\"\\\\%c\\\\%s\", parent->unique[1] + 1, addr->address); } \/* Ensure that the domain in the unique field is lower cased, because domains are always handled caselessly. *\/ p = Ustrrchr(addr->unique, '@'); while (*p != 0) { *p = tolower(*p); p++; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->unique); child_done(addr, tod_stamp(tod_log)); continue; } \/* Get the routing retry status, saving the two retry keys (with and without the local part) for subsequent use. If there is no retry record for the standard address routing retry key, we look for the same key with the sender attached, because this form is used by the smtp transport after a 4xx response to RCPT when address_retry_include_sender is true. *\/ addr->domain_retry_key = string_sprintf(\"R:%s\", addr->domain); addr->address_retry_key = string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain); if (dbm_file) { domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key); if ( domain_retry_record && now - domain_retry_record->time_stamp > retry_data_expire ) domain_retry_record = NULL; \/* Ignore if too old *\/ address_retry_record = dbfn_read(dbm_file, addr->address_retry_key); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire ) address_retry_record = NULL; \/* Ignore if too old *\/ if (!address_retry_record) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); address_retry_record = dbfn_read(dbm_file, altkey); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire) address_retry_record = NULL; \/* Ignore if too old *\/ } } else domain_retry_record = address_retry_record = NULL; DEBUG(D_deliver|D_retry) { if (!domain_retry_record) debug_printf(\"no domain retry record\\n\"); if (!address_retry_record) debug_printf(\"no address retry record\\n\"); } \/* If we are sending a message down an existing SMTP connection, we must assume that the message which created the connection managed to route an address to that connection. We do not want to run the risk of taking a long time over routing here, because if we do, the server at the other end of the connection may time it out. This is especially true for messages with lots of addresses. For this kind of delivery, queue_running is not set, so we would normally route all addresses. We take a pragmatic approach and defer routing any addresses that have any kind of domain retry record. That is, we don't even look at their retry times. It doesn't matter if this doesn't work occasionally. This is all just an optimization, after all. The reason for not doing the same for address retries is that they normally arise from 4xx responses, not DNS timeouts. *\/ if (continue_hostname && domain_retry_record) { addr->message = US\"reusing SMTP connection skips previous routing defer\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* If we are in a queue run, defer routing unless there is no retry data or we've passed the next retry time, or this message is forced. In other words, ignore retry data when not in a queue run. However, if the domain retry time has expired, always allow the routing attempt. If it fails again, the address will be failed. This ensures that each address is routed at least once, even after long-term routing failures. If there is an address retry, check that too; just wait for the next retry time. This helps with the case when the temporary error on the address was really message-specific rather than address specific, since it allows other messages through. We also wait for the next retry time if this is a message sent down an existing SMTP connection (even though that will be forced). Otherwise there will be far too many attempts for an address that gets a 4xx error. In fact, after such an error, we should not get here because, the host should not be remembered as one this message needs. However, there was a bug that used to cause this to happen, so it is best to be on the safe side. Even if we haven't reached the retry time in the hints, there is one more check to do, which is for the ultimate address timeout. We only do this check if there is an address retry record and there is not a domain retry record; this implies that previous attempts to handle the address had the retry_use_local_parts option turned on. We use this as an approximation for the destination being like a local delivery, for example delivery over LMTP to an IMAP message store. In this situation users are liable to bump into their quota and thereby have intermittently successful deliveries, which keep the retry record fresh, which can lead to us perpetually deferring messages. *\/ else if ( ( f.queue_running && !f.deliver_force || continue_hostname ) && ( ( domain_retry_record && now < domain_retry_record->next_try && !domain_retry_record->expired ) || ( address_retry_record && now < address_retry_record->next_try ) ) && ( domain_retry_record || !address_retry_record || !retry_ultimate_address_timeout(addr->address_retry_key, addr->domain, address_retry_record, now) ) ) { addr->message = US\"retry time not reached\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* The domain is OK for routing. Remember if retry data exists so it can be cleaned up after a successful delivery. *\/ else { if (domain_retry_record || address_retry_record) setflag(addr, af_dr_retry_exists); addr->next = addr_route; addr_route = addr; DEBUG(D_deliver|D_route) debug_printf(\"%s: queued for routing\\n\", addr->address); } } \/* The database is closed while routing is actually happening. Requests to update it are put on a chain and all processed together at the end. *\/ if (dbm_file) dbfn_close(dbm_file); \/* If queue_domains is set, we don't even want to try routing addresses in those domains. During queue runs, queue_domains is forced to be unset. Optimize by skipping this pass through the addresses if nothing is set. *\/ if (!f.deliver_force && queue_domains) { address_item *okaddr = NULL; while (addr_route) { address_item *addr = addr_route; addr_route = addr->next; deliver_domain = addr->domain; \/* set $domain *\/ if ((rc = match_isinlist(addr->domain, (const uschar **)&queue_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != OK) if (rc == DEFER) { addr->basic_errno = ERRNO_LISTDEFER; addr->message = US\"queue_domains lookup deferred\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } else { addr->next = okaddr; okaddr = addr; } else { addr->basic_errno = ERRNO_QUEUE_DOMAIN; addr->message = US\"domain is in queue_domains\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } } addr_route = okaddr; } \/* Now route those addresses that are not deferred. *\/ while (addr_route) { int rc; address_item *addr = addr_route; const uschar *old_domain = addr->domain; uschar *old_unique = addr->unique; addr_route = addr->next; addr->next = NULL; \/* Just in case some router parameter refers to it. *\/ if (!(return_path = addr->prop.errors_address)) return_path = sender_address; \/* If a router defers an address, add a retry item. Whether or not to use the local part in the key is a property of the router. *\/ if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new, &addr_succeed, v_none)) == DEFER) retry_add_item(addr, addr->router->retry_use_local_part ? string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain) : string_sprintf(\"R:%s\", addr->domain), 0); \/* Otherwise, if there is an existing retry record in the database, add retry items to delete both forms. We must also allow for the possibility of a routing retry that includes the sender address. Since the domain might have been rewritten (expanded to fully qualified) as a result of routing, ensure that the rewritten form is also deleted. *\/ else if (testflag(addr, af_dr_retry_exists)) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); retry_add_item(addr, altkey, rf_delete); retry_add_item(addr, addr->address_retry_key, rf_delete); retry_add_item(addr, addr->domain_retry_key, rf_delete); if (Ustrcmp(addr->domain, old_domain) != 0) retry_add_item(addr, string_sprintf(\"R:%s\", old_domain), rf_delete); } \/* DISCARD is given for :blackhole: and \"seen finish\". The event has been logged, but we need to ensure the address (and maybe parents) is marked done. *\/ if (rc == DISCARD) { address_done(addr, tod_stamp(tod_log)); continue; \/* route next address *\/ } \/* The address is finished with (failed or deferred). *\/ if (rc != OK) { (void)post_process_one(addr, rc, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* route next address *\/ } \/* The address has been routed. If the router changed the domain, it will also have changed the unique address. We have to test whether this address has already been delivered, because it's the unique address that finally gets recorded. *\/ if ( addr->unique != old_unique && tree_search(tree_nonrecipients, addr->unique) != 0 ) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: \" \"discarded\\n\", addr->address); if (addr_remote == addr) addr_remote = addr->next; else if (addr_local == addr) addr_local = addr->next; } \/* If the router has same_domain_copy_routing set, we are permitted to copy the routing for any other addresses with the same domain. This is an optimisation to save repeated DNS lookups for \"standard\" remote domain routing. The option is settable only on routers that generate host lists. We play it very safe, and do the optimization only if the address is routed to a remote transport, there are no header changes, and the domain was not modified by the router. *\/ if ( addr_remote == addr && addr->router->same_domain_copy_routing && !addr->prop.extra_headers && !addr->prop.remove_headers && old_domain == addr->domain ) { address_item **chain = &addr_route; while (*chain) { address_item *addr2 = *chain; if (Ustrcmp(addr2->domain, addr->domain) != 0) { chain = &(addr2->next); continue; } \/* Found a suitable address; take it off the routing list and add it to the remote delivery list. *\/ *chain = addr2->next; addr2->next = addr_remote; addr_remote = addr2; \/* Copy the routing data *\/ addr2->domain = addr->domain; addr2->router = addr->router; addr2->transport = addr->transport; addr2->host_list = addr->host_list; addr2->fallback_hosts = addr->fallback_hosts; addr2->prop.errors_address = addr->prop.errors_address; copyflag(addr2, addr, af_hide_child); copyflag(addr2, addr, af_local_host_removed); DEBUG(D_deliver|D_route) debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\" \"routing %s\\n\" \"Routing for %s copied from %s\\n\", addr2->address, addr2->address, addr->address); } } } \/* Continue with routing the next address. *\/ } \/* Loop to process any child addresses that the routers created, and any rerouted addresses that got put back on the new chain. *\/ \/* Debugging: show the results of the routing *\/ DEBUG(D_deliver|D_retry|D_route) { address_item *p; debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"After routing:\\n Local deliveries:\\n\"); for (p = addr_local; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Remote deliveries:\\n\"); for (p = addr_remote; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Failed addresses:\\n\"); for (p = addr_failed; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Deferred addresses:\\n\"); for (p = addr_defer; p; p = p->next) debug_printf(\" %s\\n\", p->address); } \/* Free any resources that were cached during routing. *\/ search_tidyup(); route_tidyup(); \/* These two variables are set only during routing, after check_local_user. Ensure they are not set in transports. *\/ local_user_gid = (gid_t)(-1); local_user_uid = (uid_t)(-1); \/* Check for any duplicate addresses. This check is delayed until after routing, because the flexibility of the routing configuration means that identical addresses with different parentage may end up being redirected to different addresses. Checking for duplicates too early (as we previously used to) makes this kind of thing not work. *\/ do_duplicate_check(&addr_local); do_duplicate_check(&addr_remote); \/* When acting as an MUA wrapper, we proceed only if all addresses route to a remote transport. The check that they all end up in one transaction happens in the do_remote_deliveries() function. *\/ if ( mua_wrapper && (addr_local || addr_failed || addr_defer) ) { address_item *addr; uschar *which, *colon, *msg; if (addr_local) { addr = addr_local; which = US\"local\"; } else if (addr_defer) { addr = addr_defer; which = US\"deferred\"; } else { addr = addr_failed; which = US\"failed\"; } while (addr->parent) addr = addr->parent; if (addr->message) { colon = US\": \"; msg = addr->message; } else colon = msg = US\"\"; \/* We don't need to log here for a forced failure as it will already have been logged. Defer will also have been logged, but as a defer, so we do need to do the failure logging. *\/ if (addr != addr_failed) log_write(0, LOG_MAIN, \"** %s routing yielded a %s delivery\", addr->address, which); \/* Always write an error to the caller *\/ fprintf(stderr, \"routing %s yielded a %s delivery%s%s\\n\", addr->address, which, colon, msg); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* If this is a run to continue deliveries to an external channel that is already set up, defer any local deliveries. *\/ if (continue_transport) { if (addr_defer) { address_item *addr = addr_defer; while (addr->next) addr = addr->next; addr->next = addr_local; } else addr_defer = addr_local; addr_local = NULL; } \/* Because address rewriting can happen in the routers, we should not really do ANY deliveries until all addresses have been routed, so that all recipients of the message get the same headers. However, this is in practice not always possible, since sometimes remote addresses give DNS timeouts for days on end. The pragmatic approach is to deliver what we can now, saving any rewritten headers so that at least the next lot of recipients benefit from the rewriting that has already been done. If any headers have been rewritten during routing, update the spool file to remember them for all subsequent deliveries. This can be delayed till later if there is only address to be delivered - if it succeeds the spool write need not happen. *\/ if ( f.header_rewritten && ( addr_local && (addr_local->next || addr_remote) || addr_remote && addr_remote->next ) ) { \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); f.header_rewritten = FALSE; } \/* If there are any deliveries to be and we do not already have the journal file, create it. This is used to record successful deliveries as soon as possible after each delivery is known to be complete. A file opened with O_APPEND is used so that several processes can run simultaneously. The journal is just insurance against crashes. When the spool file is ultimately updated at the end of processing, the journal is deleted. If a journal is found to exist at the start of delivery, the addresses listed therein are added to the non-recipients. *\/ if (addr_local || addr_remote) { if (journal_fd < 0) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if ((journal_fd = Uopen(fname, #ifdef O_CLOEXEC O_CLOEXEC | #endif O_WRONLY|O_APPEND|O_CREAT|O_EXCL, SPOOL_MODE)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't open journal file %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } \/* Set the close-on-exec flag, make the file owned by Exim, and ensure that the mode is correct - the group setting doesn't always seem to get set automatically. *\/ if( fchown(journal_fd, exim_uid, exim_gid) || fchmod(journal_fd, SPOOL_MODE) #ifndef O_CLOEXEC || fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC) #endif ) { int ret = Uunlink(fname); log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't set perms on journal file %s: %s\", fname, strerror(errno)); if(ret && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } } } else if (journal_fd >= 0) { close(journal_fd); journal_fd = -1; } \/* Now we can get down to the business of actually doing deliveries. Local deliveries are done first, then remote ones. If ever the problems of how to handle fallback transports are figured out, this section can be put into a loop for handling fallbacks, though the uid switching will have to be revised. *\/ \/* Precompile a regex that is used to recognize a parameter in response to an LHLO command, if is isn't already compiled. This may be used on both local and remote LMTP deliveries. *\/ if (!regex_IGNOREQUOTA) regex_IGNOREQUOTA = regex_must_compile(US\"\\\\n250[\\\\s\\\\-]IGNOREQUOTA(\\\\s|\\\\n|$)\", FALSE, TRUE); \/* Handle local deliveries *\/ if (addr_local) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\\n\"); do_local_deliveries(); f.disable_logging = FALSE; } \/* If queue_run_local is set, we do not want to attempt any remote deliveries, so just queue them all. *\/ if (f.queue_run_local) while (addr_remote) { address_item *addr = addr_remote; addr_remote = addr->next; addr->next = NULL; addr->basic_errno = ERRNO_LOCAL_ONLY; addr->message = US\"remote deliveries suppressed\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_TRANSPORT, 0); } \/* Handle remote deliveries *\/ if (addr_remote) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\\n\"); \/* Precompile some regex that are used to recognize parameters in response to an EHLO command, if they aren't already compiled. *\/ deliver_init(); \/* Now sort the addresses if required, and do the deliveries. The yield of do_remote_deliveries is FALSE when mua_wrapper is set and all addresses cannot be delivered in one transaction. *\/ if (remote_sort_domains) sort_remote_deliveries(); if (!do_remote_deliveries(FALSE)) { log_write(0, LOG_MAIN, \"** mua_wrapper is set but recipients cannot all \" \"be delivered in one transaction\"); fprintf(stderr, \"delivery to smarthost failed (configuration problem)\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* See if any of the addresses that failed got put on the queue for delivery to their fallback hosts. We do it this way because often the same fallback host is used for many domains, so all can be sent in a single transaction (if appropriately configured). *\/ if (addr_fallback && !mua_wrapper) { DEBUG(D_deliver) debug_printf(\"Delivering to fallback hosts\\n\"); addr_remote = addr_fallback; addr_fallback = NULL; if (remote_sort_domains) sort_remote_deliveries(); do_remote_deliveries(TRUE); } f.disable_logging = FALSE; } \/* All deliveries are now complete. Ignore SIGTERM during this tidying up phase, to minimize cases of half-done things. *\/ DEBUG(D_deliver) debug_printf(\">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\\n\"); cancel_cutthrough_connection(TRUE, US\"deliveries are done\"); \/* Root privilege is no longer needed *\/ exim_setugid(exim_uid, exim_gid, FALSE, US\"post-delivery tidying\"); set_process_info(\"tidying up after delivering %s\", message_id); signal(SIGTERM, SIG_IGN); \/* When we are acting as an MUA wrapper, the smtp transport will either have succeeded for all addresses, or failed them all in normal cases. However, there are some setup situations (e.g. when a named port does not exist) that cause an immediate exit with deferral of all addresses. Convert those into failures. We do not ever want to retry, nor do we want to send a bounce message. *\/ if (mua_wrapper) { if (addr_defer) { address_item *addr, *nextaddr; for (addr = addr_defer; addr; addr = nextaddr) { log_write(0, LOG_MAIN, \"** %s mua_wrapper forced failure for deferred \" \"delivery\", addr->address); nextaddr = addr->next; addr->next = addr_failed; addr_failed = addr; } addr_defer = NULL; } \/* Now all should either have succeeded or failed. *\/ if (!addr_failed) final_yield = DELIVER_MUA_SUCCEEDED; else { host_item * host; uschar *s = addr_failed->user_message; if (!s) s = addr_failed->message; fprintf(stderr, \"Delivery failed: \"); if (addr_failed->basic_errno > 0) { fprintf(stderr, \"%s\", strerror(addr_failed->basic_errno)); if (s) fprintf(stderr, \": \"); } if ((host = addr_failed->host_used)) fprintf(stderr, \"H=%s [%s]: \", host->name, host->address); if (s) fprintf(stderr, \"%s\", CS s); else if (addr_failed->basic_errno <= 0) fprintf(stderr, \"unknown error\"); fprintf(stderr, \"\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = NULL; } } \/* In a normal configuration, we now update the retry database. This is done in one fell swoop at the end in order not to keep opening and closing (and locking) the database. The code for handling retries is hived off into a separate module for convenience. We pass it the addresses of the various chains, because deferred addresses can get moved onto the failed chain if the retry cutoff time has expired for all alternative destinations. Bypass the updating of the database if the -N flag is set, which is a debugging thing that prevents actual delivery. *\/ else if (!f.dont_deliver) retry_update(&addr_defer, &addr_failed, &addr_succeed); \/* Send DSN for successful messages if requested *\/ addr_senddsn = NULL; for (addr_dsntmp = addr_succeed; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { \/* af_ignore_error not honored here. it's not an error *\/ DEBUG(D_deliver) debug_printf(\"DSN: processing router : %s\\n\" \"DSN: processing successful delivery address: %s\\n\" \"DSN: Sender_address: %s\\n\" \"DSN: orcpt: %s flags: %d\\n\" \"DSN: envid: %s ret: %d\\n\" \"DSN: Final recipient: %s\\n\" \"DSN: Remote SMTP server supports DSN: %d\\n\", addr_dsntmp->router ? addr_dsntmp->router->name : US\"(unknown)\", addr_dsntmp->address, sender_address, addr_dsntmp->dsn_orcpt ? addr_dsntmp->dsn_orcpt : US\"NULL\", addr_dsntmp->dsn_flags, dsn_envid ? dsn_envid : US\"NULL\", dsn_ret, addr_dsntmp->address, addr_dsntmp->dsn_aware ); \/* send report if next hop not DSN aware or a router flagged \"last DSN hop\" and a report was requested *\/ if ( ( addr_dsntmp->dsn_aware != dsn_support_yes || addr_dsntmp->dsn_flags & rf_dsnlasthop ) && addr_dsntmp->dsn_flags & rf_dsnflags && addr_dsntmp->dsn_flags & rf_notify_success ) { \/* copy and relink address_item and send report with all of them at once later *\/ address_item * addr_next = addr_senddsn; addr_senddsn = store_get(sizeof(address_item)); *addr_senddsn = *addr_dsntmp; addr_senddsn->next = addr_next; } else DEBUG(D_deliver) debug_printf(\"DSN: not sending DSN success message\\n\"); } if (addr_senddsn) { pid_t pid; int fd; \/* create exim process to send message *\/ pid = child_open_exim(&fd); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim returns: %d\\n\", pid); if (pid < 0) \/* Creation of child failed *\/ { log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim failed\\n\"); } else \/* Creation of child succeeded *\/ { FILE *f = fdopen(fd, \"wb\"); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ uschar * bound; transport_ctx tctx = {{0}}; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", sender_address); \/* build unique id for MIME boundary *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); DEBUG(D_deliver) debug_printf(\"DSN: MIME boundary: %s\\n\", bound); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-generated\\n\" \"From: Mail Delivery System \\n\" \"To: %s\\n\" \"Subject: Delivery Status Notification\\n\" \"Content-Type: multipart\/report; report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\\n\" \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\" \"This message was created automatically by mail delivery software.\\n\" \" ----- The following addresses had successful delivery notifications -----\\n\", qualify_domain_sender, sender_address, bound, bound); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) fprintf(f, \"<%s> (relayed %s)\\n\\n\", addr_dsntmp->address, (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? \"via non DSN router\" : addr_dsntmp->dsn_aware == dsn_support_no ? \"to non-DSN-aware mailer\" : \"via non \\\"Remote SMTP\\\" router\" ); fprintf(f, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { if (addr_dsntmp->dsn_orcpt) fprintf(f,\"Original-Recipient: %s\\n\", addr_dsntmp->dsn_orcpt); fprintf(f, \"Action: delivered\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 2.0.0\\n\", addr_dsntmp->address); if (addr_dsntmp->host_used && addr_dsntmp->host_used->name) fprintf(f, \"Remote-MTA: dns; %s\\nDiagnostic-Code: smtp; 250 Ok\\n\\n\", addr_dsntmp->host_used->name); else fprintf(f, \"Diagnostic-Code: X-Exim; relayed via non %s router\\n\\n\", (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? \"DSN\" : \"SMTP\"); } fprintf(f, \"--%s\\nContent-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); fclose(f); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ } } \/* If any addresses failed, we must send a message to somebody, unless af_ignore_error is set, in which case no action is taken. It is possible for several messages to get sent if there are addresses with different requirements. *\/ while (addr_failed) { pid_t pid; int fd; uschar *logtod = tod_stamp(tod_log); address_item *addr; address_item *handled_addr = NULL; address_item **paddr; address_item *msgchain = NULL; address_item **pmsgchain = &msgchain; \/* There are weird cases when logging is disabled in the transport. However, there may not be a transport (address failed by a router). *\/ f.disable_logging = FALSE; if (addr_failed->transport) f.disable_logging = addr_failed->transport->disable_logging; DEBUG(D_deliver) debug_printf(\"processing failed address %s\\n\", addr_failed->address); \/* There are only two ways an address in a bounce message can get here: (1) When delivery was initially deferred, but has now timed out (in the call to retry_update() above). We can detect this by testing for af_retry_timedout. If the address does not have its own errors address, we arrange to ignore the error. (2) If delivery failures for bounce messages are being ignored. We can detect this by testing for af_ignore_error. This will also be set if a bounce message has been autothawed and the ignore_bounce_errors_after time has passed. It might also be set if a router was explicitly configured to ignore errors (errors_to = \"\"). If neither of these cases obtains, something has gone wrong. Log the incident, but then ignore the error. *\/ if (sender_address[0] == 0 && !addr_failed->prop.errors_address) { if ( !testflag(addr_failed, af_retry_timedout) && !addr_failed->prop.ignore_error) log_write(0, LOG_MAIN|LOG_PANIC, \"internal error: bounce message \" \"failure is neither frozen nor ignored (it's been ignored)\"); addr_failed->prop.ignore_error = TRUE; } \/* If the first address on the list has af_ignore_error set, just remove it from the list, throw away any saved message file, log it, and mark the recipient done. *\/ if ( addr_failed->prop.ignore_error || ( addr_failed->dsn_flags & rf_dsnflags && (addr_failed->dsn_flags & rf_notify_failure) != rf_notify_failure ) ) { addr = addr_failed; addr_failed = addr->next; if (addr->return_filename) Uunlink(addr->return_filename); log_write(0, LOG_MAIN, \"%s%s%s%s: error ignored\", addr->address, !addr->parent ? US\"\" : US\" <\", !addr->parent ? US\"\" : addr->parent->address, !addr->parent ? US\"\" : US\">\"); address_done(addr, logtod); child_done(addr, logtod); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Otherwise, handle the sending of a message. Find the error address for the first address, then send a message that includes all failed addresses that have the same error address. Note the bounce_recipient is a global so that it can be accessed by $bounce_recipient while creating a customized error message. *\/ else { if (!(bounce_recipient = addr_failed->prop.errors_address)) bounce_recipient = sender_address; \/* Make a subprocess to send a message *\/ if ((pid = child_open_exim(&fd)) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); \/* Creation of child succeeded *\/ else { int ch, rc; int filecount = 0; int rcount = 0; uschar *bcc, *emf_text; FILE * fp = fdopen(fd, \"wb\"); FILE * emf = NULL; BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0; int max = (bounce_return_size_limit\/DELIVER_IN_BUFFER_SIZE + 1) * DELIVER_IN_BUFFER_SIZE; uschar * bound; uschar *dsnlimitmsg; uschar *dsnnotifyhdr; int topt; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", bounce_recipient); \/* Scan the addresses for all that have the same errors address, removing them from the addr_failed chain, and putting them on msgchain. *\/ paddr = &addr_failed; for (addr = addr_failed; addr; addr = *paddr) if (Ustrcmp(bounce_recipient, addr->prop.errors_address ? addr->prop.errors_address : sender_address) == 0) { \/* The same - dechain *\/ *paddr = addr->next; *pmsgchain = addr; addr->next = NULL; pmsgchain = &(addr->next); } else paddr = &addr->next; \/* Not the same; skip *\/ \/* Include X-Failed-Recipients: for automatic interpretation, but do not let any one header line get too long. We do this by starting a new header every 50 recipients. Omit any addresses for which the \"hide_child\" flag is set. *\/ for (addr = msgchain; addr; addr = addr->next) { if (testflag(addr, af_hide_child)) continue; if (rcount >= 50) { fprintf(fp, \"\\n\"); rcount = 0; } fprintf(fp, \"%s%s\", rcount++ == 0 ? \"X-Failed-Recipients: \" : \",\\n \", testflag(addr, af_pfr) && addr->parent ? string_printing(addr->parent->address) : string_printing(addr->address)); } if (rcount > 0) fprintf(fp, \"\\n\"); \/* Output the standard headers *\/ if (errors_reply_to) fprintf(fp, \"Reply-To: %s\\n\", errors_reply_to); fprintf(fp, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(fp); fprintf(fp, \"To: %s\\n\", bounce_recipient); \/* generate boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(fp, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); \/* Open a template file if one is provided. Log failure to open, but carry on - default texts will be used. *\/ if (bounce_message_file) if (!(emf = Ufopen(bounce_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for error \" \"message texts: %s\", bounce_message_file, strerror(errno)); \/* Quietly copy to configured additional addresses if required. *\/ if ((bcc = moan_check_errorcopy(bounce_recipient))) fprintf(fp, \"Bcc: %s\\n\", bcc); \/* The texts for the message can be read from a template file; if there isn't one, or if it is too short, built-in texts are used. The first emf text is a Subject: and any other headers. *\/ if ((emf_text = next_emf(emf, US\"header\"))) fprintf(fp, \"%s\\n\", emf_text); else fprintf(fp, \"Subject: Mail delivery failed%s\\n\\n\", to_sender? \": returning message to sender\" : \"\"); \/* output human readable part as text\/plain section *\/ fprintf(fp, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((emf_text = next_emf(emf, US\"intro\"))) fprintf(fp, \"%s\", CS emf_text); else { fprintf(fp, \/* This message has been reworded several times. It seems to be confusing to somebody, however it is worded. I have retreated to the original, simple wording. *\/ \"This message was created automatically by mail delivery software.\\n\"); if (bounce_message_text) fprintf(fp, \"%s\", CS bounce_message_text); if (to_sender) fprintf(fp, \"\\nA message that you sent could not be delivered to one or more of its\\n\" \"recipients. This is a permanent error. The following address(es) failed:\\n\"); else fprintf(fp, \"\\nA message sent by\\n\\n <%s>\\n\\n\" \"could not be delivered to one or more of its recipients. The following\\n\" \"address(es) failed:\\n\", sender_address); } fputc('\\n', fp); \/* Process the addresses, leaving them on the msgchain if they have a file name for a return message. (There has already been a check in post_process_one() for the existence of data in the message file.) A TRUE return from print_address_information() means that the address is not hidden. *\/ paddr = &msgchain; for (addr = msgchain; addr; addr = *paddr) { if (print_address_information(addr, fp, US\" \", US\"\\n \", US\"\")) print_address_error(addr, fp, US\"\"); \/* End the final line for the address *\/ fputc('\\n', fp); \/* Leave on msgchain if there's a return file. *\/ if (addr->return_file >= 0) { paddr = &(addr->next); filecount++; } \/* Else save so that we can tick off the recipient when the message is sent. *\/ else { *paddr = addr->next; addr->next = handled_addr; handled_addr = addr; } } fputc('\\n', fp); \/* Get the next text, whether we need it or not, so as to be positioned for the one after. *\/ emf_text = next_emf(emf, US\"generated text\"); \/* If there were any file messages passed by the local transports, include them in the message. Then put the address on the handled chain. In the case of a batch of addresses that were all sent to the same transport, the return_file field in all of them will contain the same fd, and the return_filename field in the *last* one will be set (to the name of the file). *\/ if (msgchain) { address_item *nextaddr; if (emf_text) fprintf(fp, \"%s\", CS emf_text); else fprintf(fp, \"The following text was generated during the delivery \" \"attempt%s:\\n\", (filecount > 1)? \"s\" : \"\"); for (addr = msgchain; addr; addr = nextaddr) { FILE *fm; address_item *topaddr = addr; \/* List all the addresses that relate to this file *\/ fputc('\\n', fp); while(addr) \/* Insurance *\/ { print_address_information(addr, fp, US\"------ \", US\"\\n \", US\" ------\\n\"); if (addr->return_filename) break; addr = addr->next; } fputc('\\n', fp); \/* Now copy the file *\/ if (!(fm = Ufopen(addr->return_filename, \"rb\"))) fprintf(fp, \" +++ Exim error... failed to open text file: %s\\n\", strerror(errno)); else { while ((ch = fgetc(fm)) != EOF) fputc(ch, fp); (void)fclose(fm); } Uunlink(addr->return_filename); \/* Can now add to handled chain, first fishing off the next address on the msgchain. *\/ nextaddr = addr->next; addr->next = handled_addr; handled_addr = topaddr; } fputc('\\n', fp); } \/* output machine readable part *\/ #ifdef SUPPORT_I18N if (message_smtputf8) fprintf(fp, \"--%s\\n\" \"Content-type: message\/global-delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); else #endif fprintf(fp, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(fp, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(fp, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', fp); for (addr = handled_addr; addr; addr = addr->next) { host_item * hu; fprintf(fp, \"Action: failed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 5.0.0\\n\", addr->address); if ((hu = addr->host_used) && hu->name) { fprintf(fp, \"Remote-MTA: dns; %s\\n\", hu->name); #ifdef EXPERIMENTAL_DSN_INFO { const uschar * s; if (hu->address) { uschar * p = hu->port == 25 ? US\"\" : string_sprintf(\":%d\", hu->port); fprintf(fp, \"Remote-MTA: X-ip; [%s]%s\\n\", hu->address, p); } if ((s = addr->smtp_greeting) && *s) fprintf(fp, \"X-Remote-MTA-smtp-greeting: X-str; %s\\n\", s); if ((s = addr->helo_response) && *s) fprintf(fp, \"X-Remote-MTA-helo-response: X-str; %s\\n\", s); if ((s = addr->message) && *s) fprintf(fp, \"X-Exim-Diagnostic: X-str; %s\\n\", s); } #endif print_dsn_diagnostic_code(addr, fp); } fputc('\\n', fp); } \/* Now copy the message, trying to give an intelligible comment if it is too long for it all to be copied. The limit isn't strictly applied because of the buffering. There is, however, an option to suppress copying altogether. *\/ emf_text = next_emf(emf, US\"copy\"); \/* add message body we ignore the intro text from template and add the text for bounce_return_size_limit at the end. bounce_return_message is ignored in case RET= is defined we honor these values otherwise bounce_return_body is honored. bounce_return_size_limit is always honored. *\/ fprintf(fp, \"--%s\\n\", bound); dsnlimitmsg = US\"X-Exim-DSN-Information: Due to administrative limits only headers are returned\"; dsnnotifyhdr = NULL; topt = topt_add_return_path; \/* RET=HDRS? top priority *\/ if (dsn_ret == dsn_ret_hdrs) topt |= topt_no_body; else { struct stat statbuf; \/* no full body return at all? *\/ if (!bounce_return_body) { topt |= topt_no_body; \/* add header if we overrule RET=FULL *\/ if (dsn_ret == dsn_ret_full) dsnnotifyhdr = dsnlimitmsg; } \/* line length limited... return headers only if oversize *\/ \/* size limited ... return headers only if limit reached *\/ else if ( max_received_linelength > bounce_return_linesize_limit || ( bounce_return_size_limit > 0 && fstat(deliver_datafile, &statbuf) == 0 && statbuf.st_size > max ) ) { topt |= topt_no_body; dsnnotifyhdr = dsnlimitmsg; } } #ifdef SUPPORT_I18N if (message_smtputf8) fputs(topt & topt_no_body ? \"Content-type: message\/global-headers\\n\\n\" : \"Content-type: message\/global\\n\\n\", fp); else #endif fputs(topt & topt_no_body ? \"Content-type: text\/rfc822-headers\\n\\n\" : \"Content-type: message\/rfc822\\n\\n\", fp); fflush(fp); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ { \/* Dummy transport for headers add *\/ transport_ctx tctx = {{0}}; transport_instance tb = {0}; tctx.u.fd = fileno(fp); tctx.tblock = &tb; tctx.options = topt; tb.add_headers = dsnnotifyhdr; transport_write_message(&tctx, 0); } fflush(fp); \/* we never add the final text. close the file *\/ if (emf) (void)fclose(emf); fprintf(fp, \"\\n--%s--\\n\", bound); \/* Close the file, which should send an EOF to the child process that is receiving the message. Wait for it to finish. *\/ (void)fclose(fp); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ \/* In the test harness, let the child do it's thing first. *\/ if (f.running_in_test_harness) millisleep(500); \/* If the process failed, there was some disaster in setting up the error message. Unless the message is very old, ensure that addr_defer is non-null, which will have the effect of leaving the message on the spool. The failed addresses will get tried again next time. However, we don't really want this to happen too often, so freeze the message unless there are some genuine deferred addresses to try. To do this we have to call spool_write_header() here, because with no genuine deferred addresses the normal code below doesn't get run. *\/ if (rc != 0) { uschar *s = US\"\"; if (now - received_time.tv_sec < retry_maximum_timeout && !addr_defer) { addr_defer = (address_item *)(+1); f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); s = US\" (frozen)\"; } deliver_msglog(\"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); log_write(0, LOG_MAIN, \"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); } \/* The message succeeded. Ensure that the recipients that failed are now marked finished with on the spool and their parents updated. *\/ else { for (addr = handled_addr; addr; addr = addr->next) { address_done(addr, logtod); child_done(addr, logtod); } \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } } } } f.disable_logging = FALSE; \/* In case left set *\/ \/* Come here from the mua_wrapper case if routing goes wrong *\/ DELIVERY_TIDYUP: \/* If there are now no deferred addresses, we are done. Preserve the message log if so configured, and we are using them. Otherwise, sling it. Then delete the message itself. *\/ if (!addr_defer) { uschar * fname; if (message_logs) { fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); if (preserve_message_logs) { int rc; uschar * moname = spool_fname(US\"msglog.OLD\", US\"\", id, US\"\"); if ((rc = Urename(fname, moname)) < 0) { (void)directory_make(spool_directory, spool_sname(US\"msglog.OLD\", US\"\"), MSGLOG_DIRECTORY_MODE, TRUE); rc = Urename(fname, moname); } if (rc < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to move %s to the \" \"msglog.OLD directory\", fname); } else if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); } \/* Remove the two message files. *\/ fname = spool_fname(US\"input\", message_subdir, id, US\"-D\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); fname = spool_fname(US\"input\", message_subdir, id, US\"-H\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Log the end of this message, with queue time if requested. *\/ if (LOGGING(queue_time_overall)) log_write(0, LOG_MAIN, \"Completed QT=%s\", string_timesince(&received_time)); else log_write(0, LOG_MAIN, \"Completed\"); \/* Unset deliver_freeze so that we won't try to move the spool files further down *\/ f.deliver_freeze = FALSE; #ifndef DISABLE_EVENT (void) event_raise(event_action, US\"msg:complete\", NULL); #endif } \/* If there are deferred addresses, we are keeping this message because it is not yet completed. Lose any temporary files that were catching output from pipes for any of the deferred addresses, handle one-time aliases, and see if the message has been on the queue for so long that it is time to send a warning message to the sender, unless it is a mailer-daemon. If all deferred addresses have the same domain, we can set deliver_domain for the expansion of delay_warning_ condition - if any of them are pipes, files, or autoreplies, use the parent's domain. If all the deferred addresses have an error number that indicates \"retry time not reached\", skip sending the warning message, because it won't contain the reason for the delay. It will get sent at the next real delivery attempt. However, if at least one address has tried, we'd better include all of them in the message. If we can't make a process to send the message, don't worry. For mailing list expansions we want to send the warning message to the mailing list manager. We can't do a perfect job here, as some addresses may have different errors addresses, but if we take the errors address from each deferred address it will probably be right in most cases. If addr_defer == +1, it means there was a problem sending an error message for failed addresses, and there were no \"real\" deferred addresses. The value was set just to keep the message on the spool, so there is nothing to do here. *\/ else if (addr_defer != (address_item *)(+1)) { address_item *addr; uschar *recipients = US\"\"; BOOL delivery_attempted = FALSE; deliver_domain = testflag(addr_defer, af_pfr) ? addr_defer->parent->domain : addr_defer->domain; for (addr = addr_defer; addr; addr = addr->next) { address_item *otaddr; if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE; if (deliver_domain) { const uschar *d = testflag(addr, af_pfr) ? addr->parent->domain : addr->domain; \/* The domain may be unset for an address that has never been routed because the system filter froze the message. *\/ if (!d || Ustrcmp(d, deliver_domain) != 0) deliver_domain = NULL; } if (addr->return_filename) Uunlink(addr->return_filename); \/* Handle the case of one-time aliases. If any address in the ancestry of this one is flagged, ensure it is in the recipients list, suitably flagged, and that its parent is marked delivered. *\/ for (otaddr = addr; otaddr; otaddr = otaddr->parent) if (otaddr->onetime_parent) break; if (otaddr) { int i; int t = recipients_count; for (i = 0; i < recipients_count; i++) { uschar *r = recipients_list[i].address; if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i; if (Ustrcmp(otaddr->address, r) == 0) break; } \/* Didn't find the address already in the list, and did find the ultimate parent's address in the list, and they really are different (i.e. not from an identity-redirect). After adding the recipient, update the errors address in the recipients list. *\/ if ( i >= recipients_count && t < recipients_count && Ustrcmp(otaddr->address, otaddr->parent->address) != 0) { DEBUG(D_deliver) debug_printf(\"one_time: adding %s in place of %s\\n\", otaddr->address, otaddr->parent->address); receive_add_recipient(otaddr->address, t); recipients_list[recipients_count-1].errors_to = otaddr->prop.errors_address; tree_add_nonrecipient(otaddr->parent->address); update_spool = TRUE; } } \/* Except for error messages, ensure that either the errors address for this deferred address or, if there is none, the sender address, is on the list of recipients for a warning message. *\/ if (sender_address[0]) { uschar * s = addr->prop.errors_address; if (!s) s = sender_address; if (Ustrstr(recipients, s) == NULL) recipients = string_sprintf(\"%s%s%s\", recipients, recipients[0] ? \",\" : \"\", s); } } \/* Send a warning message if the conditions are right. If the condition check fails because of a lookup defer, there is nothing we can do. The warning is not sent. Another attempt will be made at the next delivery attempt (if it also defers). *\/ if ( !f.queue_2stage && delivery_attempted && ( ((addr_defer->dsn_flags & rf_dsnflags) == 0) || (addr_defer->dsn_flags & rf_notify_delay) == rf_notify_delay ) && delay_warning[1] > 0 && sender_address[0] != 0 && ( !delay_warning_condition || expand_check_condition(delay_warning_condition, US\"delay_warning\", US\"option\") ) ) { int count; int show_time; int queue_time = time(NULL) - received_time.tv_sec; \/* When running in the test harness, there's an option that allows us to fudge this time so as to get repeatability of the tests. Take the first time off the list. In queue runs, the list pointer gets updated in the calling process. *\/ if (f.running_in_test_harness && fudged_queue_times[0] != 0) { int qt = readconf_readtime(fudged_queue_times, '\/', FALSE); if (qt >= 0) { DEBUG(D_deliver) debug_printf(\"fudged queue_times = %s\\n\", fudged_queue_times); queue_time = qt; } } \/* See how many warnings we should have sent by now *\/ for (count = 0; count < delay_warning[1]; count++) if (queue_time < delay_warning[count+2]) break; show_time = delay_warning[count+1]; if (count >= delay_warning[1]) { int extra; int last_gap = show_time; if (count > 1) last_gap -= delay_warning[count]; extra = (queue_time - delay_warning[count+1])\/last_gap; show_time += last_gap * extra; count += extra; } DEBUG(D_deliver) { debug_printf(\"time on queue = %s\\n\", readconf_printtime(queue_time)); debug_printf(\"warning counts: required %d done %d\\n\", count, warning_count); } \/* We have computed the number of warnings there should have been by now. If there haven't been enough, send one, and up the count to what it should have been. *\/ if (warning_count < count) { header_line *h; int fd; pid_t pid = child_open_exim(&fd); if (pid > 0) { uschar *wmf_text; FILE *wmf = NULL; FILE *f = fdopen(fd, \"wb\"); uschar * bound; transport_ctx tctx = {{0}}; if (warn_message_file) if (!(wmf = Ufopen(warn_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for warning \" \"message texts: %s\", warn_message_file, strerror(errno)); warnmsg_recipients = recipients; warnmsg_delay = queue_time < 120*60 ? string_sprintf(\"%d minutes\", show_time\/60) : string_sprintf(\"%d hours\", show_time\/3600); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(f); fprintf(f, \"To: %s\\n\", recipients); \/* generated boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(f, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); if ((wmf_text = next_emf(wmf, US\"header\"))) fprintf(f, \"%s\\n\", wmf_text); else fprintf(f, \"Subject: Warning: message %s delayed %s\\n\\n\", message_id, warnmsg_delay); \/* output human readable part as text\/plain section *\/ fprintf(f, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((wmf_text = next_emf(wmf, US\"intro\"))) fprintf(f, \"%s\", CS wmf_text); else { fprintf(f, \"This message was created automatically by mail delivery software.\\n\"); if (Ustrcmp(recipients, sender_address) == 0) fprintf(f, \"A message that you sent has not yet been delivered to one or more of its\\n\" \"recipients after more than \"); else fprintf(f, \"A message sent by\\n\\n <%s>\\n\\n\" \"has not yet been delivered to one or more of its recipients after more than \\n\", sender_address); fprintf(f, \"%s on the queue on %s.\\n\\n\" \"The message identifier is: %s\\n\", warnmsg_delay, primary_hostname, message_id); for (h = header_list; h; h = h->next) if (strncmpic(h->text, US\"Subject:\", 8) == 0) fprintf(f, \"The subject of the message is: %s\", h->text + 9); else if (strncmpic(h->text, US\"Date:\", 5) == 0) fprintf(f, \"The date of the message is: %s\", h->text + 6); fputc('\\n', f); fprintf(f, \"The address%s to which the message has not yet been \" \"delivered %s:\\n\", !addr_defer->next ? \"\" : \"es\", !addr_defer->next ? \"is\": \"are\"); } \/* List the addresses, with error information if allowed *\/ \/* store addr_defer for machine readable part *\/ address_item *addr_dsndefer = addr_defer; fputc('\\n', f); while (addr_defer) { address_item *addr = addr_defer; addr_defer = addr->next; if (print_address_information(addr, f, US\" \", US\"\\n \", US\"\")) print_address_error(addr, f, US\"Delay reason: \"); fputc('\\n', f); } fputc('\\n', f); \/* Final text *\/ if (wmf) { if ((wmf_text = next_emf(wmf, US\"final\"))) fprintf(f, \"%s\", CS wmf_text); (void)fclose(wmf); } else { fprintf(f, \"No action is required on your part. Delivery attempts will continue for\\n\" \"some time, and this warning may be repeated at intervals if the message\\n\" \"remains undelivered. Eventually the mail delivery software will give up,\\n\" \"and when that happens, the message will be returned to you.\\n\"); } \/* output machine readable part *\/ fprintf(f, \"\\n--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f,\"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f,\"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for ( ; addr_dsndefer; addr_dsndefer = addr_dsndefer->next) { if (addr_dsndefer->dsn_orcpt) fprintf(f, \"Original-Recipient: %s\\n\", addr_dsndefer->dsn_orcpt); fprintf(f, \"Action: delayed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 4.0.0\\n\", addr_dsndefer->address); if (addr_dsndefer->host_used && addr_dsndefer->host_used->name) { fprintf(f, \"Remote-MTA: dns; %s\\n\", addr_dsndefer->host_used->name); print_dsn_diagnostic_code(addr_dsndefer, f); } fputc('\\n', f); } fprintf(f, \"--%s\\n\" \"Content-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); \/* Close and wait for child process to complete, without a timeout. If there's an error, don't update the count. *\/ (void)fclose(f); if (child_close(pid, 0) == 0) { warning_count = count; update_spool = TRUE; \/* Ensure spool rewritten *\/ } } } } \/* Clear deliver_domain *\/ deliver_domain = NULL; \/* If this was a first delivery attempt, unset the first time flag, and ensure that the spool gets updated. *\/ if (f.deliver_firsttime) { f.deliver_firsttime = FALSE; update_spool = TRUE; } \/* If delivery was frozen and freeze_tell is set, generate an appropriate message, unless the message is a local error message (to avoid loops). Then log the freezing. If the text in \"frozen_info\" came from a system filter, it has been escaped into printing characters so as not to mess up log lines. For the \"tell\" message, we turn \\n back into newline. Also, insert a newline near the start instead of the \": \" string. *\/ if (f.deliver_freeze) { if (freeze_tell && freeze_tell[0] != 0 && !f.local_error_message) { uschar *s = string_copy(frozen_info); uschar *ss = Ustrstr(s, \" by the system filter: \"); if (ss != NULL) { ss[21] = '.'; ss[22] = '\\n'; } ss = s; while (*ss != 0) { if (*ss == '\\\\' && ss[1] == 'n') { *ss++ = ' '; *ss++ = '\\n'; } else ss++; } moan_tell_someone(freeze_tell, addr_defer, US\"Message frozen\", \"Message %s has been frozen%s.\\nThe sender is <%s>.\\n\", message_id, s, sender_address); } \/* Log freezing just before we update the -H file, to minimize the chance of a race problem. *\/ deliver_msglog(\"*** Frozen%s\\n\", frozen_info); log_write(0, LOG_MAIN, \"Frozen%s\", frozen_info); } \/* If there have been any updates to the non-recipients list, or other things that get written to the spool, we must now update the spool header file so that it has the right information for the next delivery attempt. If there was more than one address being delivered, the header_change update is done earlier, in case one succeeds and then something crashes. *\/ DEBUG(D_deliver) debug_printf(\"delivery deferred: update_spool=%d header_rewritten=%d\\n\", update_spool, f.header_rewritten); if (update_spool || f.header_rewritten) \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Finished with the message log. If the message is complete, it will have been unlinked or renamed above. *\/ if (message_logs) (void)fclose(message_log); \/* Now we can close and remove the journal file. Its only purpose is to record successfully completed deliveries asap so that this information doesn't get lost if Exim (or the machine) crashes. Forgetting about a failed delivery is not serious, as trying it again is not harmful. The journal might not be open if all addresses were deferred at routing or directing. Nevertheless, we must remove it if it exists (may have been lying around from a crash during the previous delivery attempt). We don't remove the journal if a delivery subprocess failed to pass back delivery information; this is controlled by the remove_journal flag. When the journal is left, we also don't move the message off the main spool if frozen and the option is set. It should get moved at the next attempt, after the journal has been inspected. *\/ if (journal_fd >= 0) (void)close(journal_fd); if (remove_journal) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if (Uunlink(fname) < 0 && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Move the message off the spool if requested *\/ #ifdef SUPPORT_MOVE_FROZEN_MESSAGES if (f.deliver_freeze && move_frozen_messages) (void)spool_move_message(id, message_subdir, US\"\", US\"F\"); #endif } \/* Closing the data file frees the lock; if the file has been unlinked it will go away. Otherwise the message becomes available for another process to try delivery. *\/ (void)close(deliver_datafile); deliver_datafile = -1; DEBUG(D_deliver) debug_printf(\"end delivery of %s\\n\", id); \/* It is unlikely that there will be any cached resources, since they are released after routing, and in the delivery subprocesses. However, it's possible for an expansion for something afterwards (for example, expand_check_condition) to do a lookup. We must therefore be sure everything is released. *\/ search_tidyup(); acl_where = ACL_WHERE_UNKNOWN; return final_yield; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":253694,"input":"int CLASS parse_tiff_ifd(int base) { unsigned entries, tag, type, len, plen = 16, save; int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1}; unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095}; unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd \/ sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); \/\/ Recover tiff-read position!! continue; } if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : ((ifd + 1) << 20)), type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, \"SONY\", 4) || (!strncasecmp(make, \"Hasselblad\", 10) && (!strncasecmp(model, \"Stellar\", 7) || !strncasecmp(model, \"Lunar\", 5) || !strncasecmp(model, \"HV\", 2)))) { switch (tag) { case 0x7300: \/\/ SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2(); break; case 0x7312: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: if (len == 3) { FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } else if (len == 1) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); } break; } } #endif switch (tag) { case 1: if (len == 4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; break; #ifdef LIBRAW_LIBRARY_BUILD case 10: if (pana_raw && len == 1 && type == 3) { pana_bpp = get2(); } break; #endif case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { imgdata.color.linear_max[tag - 14] = get2(); if (tag == 15) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag - 17) * 2] = get2() \/ 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; case 0x0120: if (pana_raw) { unsigned sorder = order; unsigned long sbase = base; base = ftell(ifp); order = get2(); fseek(ifp, 2, SEEK_CUR); fseek(ifp, get4()-8, SEEK_CUR); parse_tiff_ifd (base); base = sbase; order = sorder; } break; case 0x2009: if ((pana_encoding == 4) || (pana_encoding == 5)) { int n = MIN (8, len); int permut[8] = {3, 2, 1, 0, 3+4, 2+4, 1+4, 0+4}; imgdata.makernotes.panasonic.BlackLevelDim = len; for (int i=0; i < n; i++) { imgdata.makernotes.panasonic.BlackLevel[permut[i]] = (float) (get2()) \/ (float) (powf(2.f, 14.f-pana_bpp)); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) { pana_black[tag - 28] = get2(); } else #endif { cblack[tag - 28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag - 36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]>0.001f) break; fseek(ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 45: if (pana_raw && len == 1 && type == 3) { pana_encoding = get2(); } break; #endif case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: \/* Fuji HS10 table *\/ fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; case 2: case 256: case 61441: \/* ImageWidth *\/ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: \/* ImageHeight *\/ tiff_ifd[ifd].t_height = getint(type); break; case 258: \/* BitsPerSample *\/ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24 : 80; break; case 259: \/* Compression *\/ tiff_ifd[ifd].comp = getint(type); break; case 262: \/* PhotometricInterpretation *\/ tiff_ifd[ifd].phint = get2(); break; case 270: \/* ImageDescription *\/ fread(desc, 512, 1, ifp); break; case 271: \/* Make *\/ fgets(make, 64, ifp); break; case 272: \/* Model *\/ fgets(model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: \/* Panasonic RW2 offset *\/ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: \/* StripOffset *\/ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); \/\/ restore position } \/* fallback *\/ #endif case 513: \/* JpegIFOffset *\/ case 61447: tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width \/= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: \/* Orientation *\/ tiff_ifd[ifd].t_flip = \"50132467\"[get2() & 7] - '0'; break; case 277: \/* SamplesPerPixel *\/ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: \/* StripByteCounts *\/ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_byte_counts[i] = get4(); fseek(ifp, sav, SEEK_SET); \/\/ restore position } \/* fallback *\/ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: \/\/ FujiFilm \"As Shot\" FORC3 cam_mul[(4 - c) % 3] = getint(type); break; case 305: case 11: \/* Software *\/ if ((pana_raw) && (tag == 11) && (type == 3)) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.makernotes.panasonic.Compression = get2(); #endif break; } fgets(software, 64, ifp); if (!strncmp(software, \"Adobe\", 5) || !strncmp(software, \"dcraw\", 5) || !strncmp(software, \"UFRaw\", 5) || !strncmp(software, \"Bibble\", 6) || !strcmp(software, \"Digital Photo Professional\")) is_raw = 0; break; case 306: \/* DateTime *\/ get_timestamp(0); break; case 315: \/* Artist *\/ fread(artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: \/* TileWidth *\/ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: \/* TileLength *\/ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: \/* TileOffsets *\/ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4(); break; case 330: \/* SubIFDs *\/ if (!strcmp(model, \"DSLR-A100\") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4() + base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd \/ sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, \"Hasselblad\", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek(ifp, ftell(ifp) + 4, SEEK_SET); fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; } #endif if (len > 1000) len = 1000; \/* 1000 SubIFDs is enough *\/ while (len--) { i = ftell(ifp); fseek(ifp, get4() + base, SEEK_SET); if (parse_tiff_ifd(base)) break; fseek(ifp, i + 4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy(make, \"Sarnoff\"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char *)malloc(xmplen = len + 1); fread(xmpdata, len, 1, ifp); xmpdata[len] = 0; } break; #endif case 28688: FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff; for (i = 0; i < 5; i++) for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++) curve[j] = curve[j - 1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta(ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: \/\/ Sony matrix, Sony_SR2SubIFD_0x7800 for (i = 0; i < 3; i++) { float num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[i][c] = (float)((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] \/ num; } break; #endif case 29456: \/\/ Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _(\"...Sony black: %u cblack: %u %u %u %u\\n\"), black, cblack[0], cblack[1], cblack[2], cblack[3]); #endif break; case 33405: \/* Model2 *\/ fgets(model2, 64, ifp); break; case 33421: \/* CFARepeatPatternDim *\/ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: \/* CFAPattern *\/ if (filters == 9) { FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: \/* Kodak P-series *\/ if (len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if (len > 0) { if ((plen = len) > 16) plen = 16; fread(cfa_pat, 1, plen, ifp); for (colors = cfa = i = 0; i < plen && colors < 4; i++) { if(cfa_pat[i] > 31) continue; \/\/ Skip wrong data colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy(cfa_pc, \"\\003\\004\\005\", 3); \/* CMY *\/ if (cfa == 072) memcpy(cfa_pc, \"\\005\\003\\004\\001\", 4); \/* GMCY *\/ goto guess_cfa_pc; } break; case 33424: case 65024: fseek(ifp, get4() + base, SEEK_SET); parse_kodak_ifd(base); break; case 33434: \/* ExposureTime *\/ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: \/* FNumber *\/ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD \/\/ IB start case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) \/\/ TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: \/\/ FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: \/\/ BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: \/\/ LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: \/\/ LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: \/\/ DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: \/\/ LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: \/\/ LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, \"----\", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) \/ 2.0f)); break; \/\/ IB end #endif case 34306: \/* Leaf white balance *\/ FORC4 { int q = get2(); if(q) cam_mul[c ^ 1] = 4096.0 \/ q; } break; case 34307: \/* Leaf CatchLight color matrix *\/ fread(software, 1, 7, ifp); if (strncmp(software, \"MATRIX\", 6)) break; colors = 4; for (raw_color = i = 0; i < 3; i++) { FORC4 fscanf(ifp, \"%f\", &rgb_cam[i][c ^ 1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] \/= MAX(1, num); } break; case 34310: \/* Leaf metadata *\/ parse_mos(ftell(ifp)); case 34303: strcpy(make, \"Leaf\"); break; case 34665: \/* EXIF tag *\/ fseek(ifp, get4() + base, SEEK_SET); parse_exif(base); break; case 34853: \/* GPSInfo tag *\/ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: \/* InterColorProfile *\/ case 50831: \/* AsShotICCProfile *\/ profile_offset = ftell(ifp); profile_length = len; break; case 37122: \/* CompressedBitsPerPixel *\/ kodak_cbpp = get4(); break; case 37386: \/* FocalLength *\/ focal_len = getreal(type); break; case 37393: \/* ImageNumber *\/ shot_order = getint(type); break; case 37400: \/* old Kodak KDC tag *\/ for (raw_color = i = 0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: \/* Imacon tags *\/ strcpy(make, \"Imacon\"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek(ifp, 38, SEEK_CUR); case 46274: fseek(ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952) { height = 5412; width = 7216; left_margin = 7; filters = 0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek(ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek(ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width, height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf(model, \"Ixpress %d-Mp\", height * width \/ 1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: \/* Sinar tag *\/ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread(cbuf, 1, len, ifp); #else if (fread(cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; \/\/ cbuf to be free'ed in recycle #endif cbuf[len - 1] = 0; for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\\n')) if (!strncmp(++cp, \"Neutral \", 8)) sscanf(cp + 8, \"%f %f %f\", cam_mul, cam_mul + 1, cam_mul + 2); free(cbuf); break; case 50458: if (!make[0]) strcpy(make, \"Hasselblad\"); break; case 50459: \/* Hasselblad tag *\/ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek(ifp, j + (get2(), get4()), SEEK_SET); parse_tiff_ifd(j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: \/* DNGVersion *\/ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy(make, \"DNG\"); is_raw = 1; break; case 50708: \/* UniqueCameraModel *\/ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets(make, 64, ifp); #else strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } break; case 50710: \/* CFAPlaneColor *\/ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread(cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i = 16; i--;) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: \/* CFALayout *\/ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: \/* LinearizationTable *\/ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE; tiff_ifd[ifd].lineartable_offset = ftell(ifp); tiff_ifd[ifd].lineartable_len = len; #endif linear_table(len); break; case 50713: \/* BlackLevelRepeatDim *\/ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_fcblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_fcblack[5] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) \/ sizeof(cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_fcblack[4] = tiff_ifd[ifd].dng_levels.dng_fcblack[5] = tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00d: if (strcmp(model, \"X-A3\") && strcmp(model, \"X-A10\") && strcmp(model, \"X-A5\") && strcmp(model, \"X-A20\")) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1]; } break; case 0xf00c: if (strcmp(model, \"X-A3\") && strcmp(model, \"X-A10\") && strcmp(model, \"X-A5\") && strcmp(model, \"X-A20\")) { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) && (libraw_internal_data.unpacker_data.lenRAFData < 10240000)) { INT64 f_save = ftell(ifp); ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData); fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); int fj, found = 0; for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++) { if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2])) { if (rafdata[fi - 15] != fwb[0]) continue; for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3) { imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] = imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2]; } fi += 0x60; for (fj = fi; fj < (fi + 15); fj += 3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { fj = fj - 93; for (int iCCT = 0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj]; } } free(rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel, len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len), 64); case 50714: \/* BlackLevel *\/ #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) \/\/ LinearDNG, per-channel black { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; for (i = 0; i < 4 && i < len; i++) { tiff_ifd[ifd].dng_levels.dng_fcblack[i] = getreal(type); tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = tiff_ifd[ifd].dng_levels.dng_fcblack[i]+0.5; } tiff_ifd[ifd].dng_levels.dng_fblack = tiff_ifd[ifd].dng_levels.dng_black = black = 0; } else #endif if ((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_fblack = getreal(type); black = tiff_ifd[ifd].dng_levels.dng_black = tiff_ifd[ifd].dng_levels.dng_fblack; #else black = getreal(type); #endif } else if (cblack[4] * cblack[5] <= len) { FORC(cblack[4] * cblack[5]) #ifdef LIBRAW_LIBRARY_BUILD { tiff_ifd[ifd].dng_levels.dng_fcblack[6+c] = getreal(type); cblack[6+c] = tiff_ifd[ifd].dng_levels.dng_fcblack[6+c]; } #else cblack[6 + c] = getreal(type); #endif black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 50714) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; FORC(cblack[4] * cblack[5]) tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c]; tiff_ifd[ifd].dng_levels.dng_fblack = 0; tiff_ifd[ifd].dng_levels.dng_black = 0; FORC4 tiff_ifd[ifd].dng_levels.dng_fcblack[c] = tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0; } #endif } break; case 50715: \/* BlackLevelDeltaH *\/ case 50716: \/* BlackLevelDeltaV *\/ for (num = i = 0; i < len && i < 65536; i++) num += getreal(type); if(len>0) { black += num \/ len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_fblack += num\/float(len); tiff_ifd[ifd].dng_levels.dng_black += num \/ len + 0.5; tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; #endif } break; case 50717: \/* WhiteLevel *\/ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE; tiff_ifd[ifd].dng_levels.dng_whitelevel[0] = #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1) \/\/ Linear DNG case for (i = 1; i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type); #endif break; case 50718: \/* DefaultScale *\/ { float q1 = getreal(type); float q2 = getreal(type); if(q1 > 0.00001f && q2 > 0.00001f) { pixel_aspect = q1\/q2; if (pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; } } break; #ifdef LIBRAW_LIBRARY_BUILD case 50719: \/* DefaultCropOrigin *\/ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN; tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type); if (!strncasecmp(make, \"SONY\", 4)) { imgdata.sizes.raw_crop.cleft = tiff_ifd[ifd].dng_levels.default_crop[0]; imgdata.sizes.raw_crop.ctop = tiff_ifd[ifd].dng_levels.default_crop[1]; } } break; case 50720: \/* DefaultCropSize *\/ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE; tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type); if (!strncasecmp(make, \"SONY\", 4)) { imgdata.sizes.raw_crop.cwidth = tiff_ifd[ifd].dng_levels.default_crop[2]; imgdata.sizes.raw_crop.cheight = tiff_ifd[ifd].dng_levels.default_crop[3]; } } break; case 0x74c7: if ((len == 2) && !strncasecmp(make, \"SONY\", 4)) { imgdata.makernotes.sony.raw_crop.cleft = get4(); imgdata.makernotes.sony.raw_crop.ctop = get4(); } break; case 0x74c8: if ((len == 2) && !strncasecmp(make, \"SONY\", 4)) { imgdata.makernotes.sony.raw_crop.cwidth = get4(); imgdata.makernotes.sony.raw_crop.cheight = get4(); } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50778: tiff_ifd[ifd].dng_color[0].illuminant = get2(); tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 50779: tiff_ifd[ifd].dng_color[1].illuminant = get2(); tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; #endif case 50721: \/* ColorMatrix1 *\/ case 50722: \/* ColorMatrix2 *\/ { int chan = (len == 9)? 3 : (len == 12?4:0); #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721 ? 0 : 1; if(chan) tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX; #endif FORC(chan) for (j = 0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].colormatrix[c][j] = #endif cm[c][j] = getreal(type); } use_cm = 1; } break; case 0xc714: \/* ForwardMatrix1 *\/ case 0xc715: \/* ForwardMatrix2 *\/ { int chan = (len == 9)? 3 : (len == 12?4:0); #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714 ? 0 : 1; if(chan) tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; #endif for (j = 0; j < 3; j++) FORC(chan) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] = #endif fm[j][c] = getreal(type); } } break; case 50723: \/* CameraCalibration1 *\/ case 50724: \/* CameraCalibration2 *\/ { int chan = (len == 9)? 3 : (len == 16?4:0); #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723 ? 0 : 1; if(chan) tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION; #endif for (i = 0; i < chan; i++) FORC(chan) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[j].calibration[i][c] = #endif cc[i][c] = getreal(type); } } break; case 50727: \/* AnalogBalance *\/ #ifdef LIBRAW_LIBRARY_BUILD if(len>=3) tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE; #endif for(c = 0; c < len && c < 4; c++) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.analogbalance[c] = #endif ab[c] = getreal(type); } break; case 50728: \/* AsShotNeutral *\/ #ifdef LIBRAW_LIBRARY_BUILD if(len>=3) tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ASSHOTNEUTRAL; for(c = 0; c < len && c < 4; c++) tiff_ifd[ifd].dng_levels.asshotneutral[c] = asn[c] = getreal(type); #else FORCC asn[c] = getreal(type); #endif break; case 50729: \/* AsShotWhiteXY *\/ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] \/= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: \/* DNG: Baseline Exposure *\/ baseline_exposure = getreal(type); break; #endif \/\/ IB start case 50740: \/* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private *\/ #ifdef LIBRAW_LIBRARY_BUILD if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SKIP_MAKERNOTES)) { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, \"Adobe\")) { order = 0x4d4d; \/\/ Adobe header is always in \"MM\" \/ big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, \"MakN\", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; INT64 save_pos = ifp->tell(); parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); curr_pos = save_pos + MakN_length - 6; fseek(ifp, curr_pos, SEEK_SET); fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, \"SR2 \", 4)) { order = 0x4d4d; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; unsigned *buf_SR2; uchar *cbuf_SR2; unsigned icbuf_SR2; unsigned entries, tag, type, len, save; int ival; unsigned SR2SubIFDOffset = 0; unsigned SR2SubIFDLength = 0; unsigned SR2SubIFDKey = 0; int base = curr_pos + 6 - pos_in_original_raw; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 0x7200) { SR2SubIFDOffset = get4(); } else if (tag == 0x7201) { SR2SubIFDLength = get4(); } else if (tag == 0x7221) { SR2SubIFDKey = get4(); } fseek(ifp, save, SEEK_SET); } if (SR2SubIFDLength && (SR2SubIFDLength < 10240000) && (buf_SR2 = (unsigned *)malloc(SR2SubIFDLength+1024))) \/\/ 1024b for safety { fseek(ifp, SR2SubIFDOffset + base, SEEK_SET); fread(buf_SR2, SR2SubIFDLength, 1, ifp); sony_decrypt(buf_SR2, SR2SubIFDLength \/ 4, 1, SR2SubIFDKey); cbuf_SR2 = (uchar *)buf_SR2; entries = sget2(cbuf_SR2); icbuf_SR2 = 2; while (entries--) { tag = sget2(cbuf_SR2 + icbuf_SR2); icbuf_SR2 += 2; type = sget2(cbuf_SR2 + icbuf_SR2); icbuf_SR2 += 2; len = sget4(cbuf_SR2 + icbuf_SR2); icbuf_SR2 += 4; if (len * (\"11124811248484\"[type < 14 ? type : 0] - '0') > 4) { ival = sget4(cbuf_SR2 + icbuf_SR2) - SR2SubIFDOffset; } else { ival = icbuf_SR2; } if(ival > SR2SubIFDLength) \/\/ points out of orig. buffer size break; \/\/ END processing. Generally we should check against SR2SubIFDLength minus 6 of 8, depending on tag, but we allocated extra 1024b for buffer, so this does not matter icbuf_SR2 += 4; switch (tag) { case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = sget2(cbuf_SR2 + ival + 2 * c); break; case 0x7312: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = sget2(cbuf_SR2 + ival + 2 * c); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; } } free(buf_SR2); } } \/* SR2 processed *\/ break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, \"PENTAX \") || !strcmp(mbuf, \"SAMSUNG\")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } \/\/ IB end #endif if (dng_version) break; parse_minolta(j = get4() + base); fseek(ifp, j, SEEK_SET); parse_tiff_ifd(base); break; case 50752: read_shorts(cr2_slice, 3); break; case 50829: \/* ActiveArea *\/ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: \/* MaskedAreas *\/ for (i = 0; i < len && i < 32; i++) ((int *)mask)[i] = getint(type); black = 0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50970: \/* PreviewColorSpace *\/ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS; tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type); break; #endif case 51009: \/* OpcodeList2 *\/ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2; tiff_ifd[ifd].opcode2_offset = #endif meta_offset = ftell(ifp); break; case 64772: \/* Kodak P-series *\/ if (len < 13) break; fseek(ifp, 16, SEEK_CUR); data_offset = get4(); fseek(ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets(model2, 64, ifp); } fseek(ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length))) { fseek(ifp, sony_offset, SEEK_SET); fread(buf, sony_length, 1, ifp); sony_decrypt(buf, sony_length \/ 4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite(buf, sony_length, 1, ifp); fseek(ifp, 0, SEEK_SET); parse_tiff_ifd(-sony_offset); fclose(ifp); } ifp = sfp; #else if (!ifp->tempbuffer_open(buf, sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free(buf); } for (i = 0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC if(fabs(asn[c])>0.0001) cam_mul[c] = 1 \/ asn[c]; } if (!use_cm) FORCC if(fabs(cc[c][c])>0.0001) pre_mul[c] \/= cc[c][c]; return 0; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":332548,"input":"void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif \/* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. *\/ if (!strncmp(make, \"Nokia\", 5)) return; fread(buf, 1, 10, ifp); if (!strncmp(buf, \"KDK\", 3) || \/* these aren't TIFF tables *\/ !strncmp(buf, \"VER\", 3) || !strncmp(buf, \"IIII\", 4) || !strncmp(buf, \"MMMM\", 4)) return; if (!strncmp(buf, \"KC\", 2) || \/* Konica KD-400Z, KD-510Z *\/ !strncmp(buf, \"MLY\", 3)) { \/* Minolta DiMAGE G series *\/ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, \"Nikon\")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, \"OLYMPUS\") || !strcmp(buf, \"PENTAX \")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, \"SONY\", 4) || !strcmp(buf, \"Panasonic\")) { goto nf; } else if (!strncmp(buf, \"FUJIFILM\", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, \"OLYMP\") || !strcmp(buf, \"LEICA\") || !strcmp(buf, \"Ricoh\") || !strcmp(buf, \"EPSON\")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, \"AOC\") || !strcmp(buf, \"QVC\")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, \"SAMSUNG\", 7)) base = ftell(ifp); } \/\/ adjust pos & base for Leica M8\/M9\/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, \"LEICA\", 5)) { if (!strncmp(model, \"M8\", 2) || !strncasecmp(model, \"Leica M8\", 8) || !strncasecmp(model, \"LEICA X\", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, \"LEICA M (Typ 240)\", 17)) { base = 0; } else if (!strncmp(model, \"M9\", 2) || !strncasecmp(model, \"Leica M9\", 8) || !strncasecmp(model, \"M Monochrom\", 11) || !strncasecmp(model, \"Leica M Monochrom\", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, \"LEICA T\", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, \"LEICA SL\", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) continue; if (!strncmp(make, \"Canon\", 5)) { if (tag == 0x000d && len < 256000) \/\/ camera info { CanonCameraInfo = (uchar *)malloc(len); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) \/\/ Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; \/\/ M3 if (unique_id == 0x03840000) unique_id = 0x80000384; \/\/ M10 if (unique_id == 0x03940000) unique_id = 0x80000394; \/\/ M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, \"FUJI\", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), \"%s %s\", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, \"%2x\", &c); j += 2) ystr[j \/ 2] = c; ystr[ynum_len \/ 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), \"%s %s %d:%s:%s\", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), \"%s %d:%s:%s %s\", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), \"%s %s %d:%s:%s %s\", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(make, \"LEICA\", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, \"LEICA M\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, \"LEICA S\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, \"NIKON\", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) \/ (float)c; } else if (tag == 0x0082) \/\/ lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) \/\/ lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) \/\/ lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) \/\/ lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 \/ c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops \/ 12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) \/\/ contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: \/\/ encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) \/\/ contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, \"OLYMPUS\", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) \/ 2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(make, \"RICOH\", 5)) && !strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { \/\/ sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, \"%02x\", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, \"%8s\", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, \"%02x%02x%02x%02x\", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%02x%02x%02x%02x\", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, \"RICOH\", 5) && strncmp(model, \"PENTAX\", 6)) { if ((tag == 0x0005) && !strncmp(model, \"GXR\", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, \"GXR\", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(model, \"PENTAX\", 6) || (!strncmp(make, \"SAMSUNG\", 7) && dng_version)) && strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() \/ 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() \/ 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) \/ 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) \/ 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) \/\/ Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) \/ sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%d\", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek(ifp, 2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) \/\/ Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, \" \"); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, \"SAMSUNG\", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, \"NX mini\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() \/ 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, \"SONY\", 4) || !strncasecmp(make, \"Konica\", 6) || !strncasecmp(make, \"Minolta\", 7) || (!strncasecmp(make, \"Hasselblad\", 10) && (!strncasecmp(model, \"Stellar\", 7) || !strncasecmp(model, \"Lunar\", 5) || !strncasecmp(model, \"Lusso\", 5) || !strncasecmp(model, \"HV\", 2)))) { ushort lid; if (tag == 0xb001) \/\/ Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free(table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && \/\/ CameraInfo strncasecmp(model, \"DSLR-A100\", 9) && strncasecmp(model, \"NEX-5C\", 6) && !strncasecmp(make, \"SONY\", 4) && ((len == 368) || \/\/ a700 (len == 5478) || \/\/ a850, a900 (len == 5506) || \/\/ a200, a300, a350 (len == 6118) || \/\/ a230, a290, a330, a380, a390 \/\/ a450, a500, a550, a560, a580 \/\/ a33, a35, a55 \/\/ NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360))) { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, \"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\", 8) && memcmp(table_buf, \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\", 8)) { switch (len) { case 368: case 5478: \/\/ a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) \/ 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) \/ 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: \/\/ CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) \/ 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) \/ 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && \/\/ WBInfoA100, needs 0xb028 processing !strncasecmp(model, \"DSLR-A100\", 9)) { fseek(ifp, 0x49dc, SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) \/\/ Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) \/\/ CameraSettings { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: \/\/ CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid \/ 8.0f - 1.0f) \/ 2.0f); } break; case 1536: case 2048: \/\/ CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) \/\/ little endian { table_buf_0x9050 = (uchar *)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free(table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar *)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, \"MC-11\"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) \/\/ Sony LensSpec { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) \/ 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) \/ 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, \"NIKON\") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, \"NIKON\") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * powf64(2.0f, float(cc) \/ 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i \/ 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i \/ 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short)i \/ -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, \"KONICA\", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, \"Canon\", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 \/* Canon rotation data is handled by EXIF.Orientation *\/ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = \"065\"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, \"Olympus\", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, \"E-410\", 5) || !strncasecmp(model, \"E-510\", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag - 0x20400102; switch (nWB) { case 0: CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1: CT = 3300; tWB = 0x100; break; case 2: CT = 3600; tWB = 0x100; break; case 3: CT = 3900; tWB = 0x100; break; case 4: CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5: CT = 4300; tWB = 0x100; break; case 6: CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7: CT = 4800; tWB = 0x100; break; case 8: CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9: CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c + 1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag - 0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, \"NIKON\", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, \"NRW \", 4)) { fseek(ifp, strcmp(buf + 4, \"0100\") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, \"PENTAX\")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, \"D50\"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, \"%d\", serial); #endif } if (tag == 0x29 && type == 1) { \/\/ Canon PowerShot G9 c = wbi < 18 ? \"012347800000005896\"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { \/\/ shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = \"66666>666;6A;:;55\"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) \/\/ Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) \/\/ Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD \/\/ not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, \"NIKON\") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { \/* Nikon Capture Note *\/ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 \/ 0x10000; cam_mul[2] = get2() * 382 * 1.173 \/ 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) \/ 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) \/ 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) \/ 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() \/ 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() \/ 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() \/ 256.0; cam_mul[2] = get2() \/ 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD \/\/ IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make, \"Olympus\", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } \/\/ IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, \"OLYMP\", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, \"Samsung\", 7)) { if (tag == 0xa020) \/\/ get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) \/\/ get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) \/ 256.0; #endif if (tag == 0xa031 && len == 9) \/\/ get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) \/ 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { \/\/ Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":202821,"input":"void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x0116; ushort table_buf_0x0116_len = 0; uchar *table_buf_0x2010; ushort table_buf_0x2010_len = 0; uchar *table_buf_0x9050; ushort table_buf_0x9050_len = 0; uchar *table_buf_0x9400; ushort table_buf_0x9400_len = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_len = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_len = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_len = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_len = 0; uchar *table_buf_0x940e; ushort table_buf_0x940e_len = 0; INT64 fsize = ifp->size(); #endif \/* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. *\/ if (!strncmp(make, \"Nokia\", 5)) return; fread(buf, 1, 10, ifp); \/* printf(\"===>>buf: 0x\"); for (int i = 0; i < sizeof buf; i ++) { printf(\"%02x\", buf[i]); } putchar('\\n'); *\/ if (!strncmp(buf, \"KDK\", 3) || \/* these aren't TIFF tables *\/ !strncmp(buf, \"VER\", 3) || !strncmp(buf, \"IIII\", 4) || !strncmp(buf, \"MMMM\", 4)) return; if (!strncmp(buf, \"KC\", 2) || \/* Konica KD-400Z, KD-510Z *\/ !strncmp(buf, \"MLY\", 3)) { \/* Minolta DiMAGE G series *\/ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, \"Nikon\")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, \"OLYMPUS\") || !strcmp(buf, \"PENTAX \")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, \"SONY\", 4) || !strcmp(buf, \"Panasonic\")) { goto nf; } else if (!strncmp(buf, \"FUJIFILM\", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, \"OLYMP\") || !strcmp(buf, \"LEICA\") || !strcmp(buf, \"Ricoh\") || !strcmp(buf, \"EPSON\")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, \"AOC\") || !strcmp(buf, \"QVC\")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, \"SAMSUNG\", 7)) base = ftell(ifp); } \/\/ adjust pos & base for Leica M8\/M9\/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, \"LEICA\", 5)) { if (!strncmp(model, \"M8\", 2) || !strncasecmp(model, \"Leica M8\", 8) || !strncasecmp(model, \"LEICA X\", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, \"LEICA M (Typ 240)\", 17)) { base = 0; } else if (!strncmp(model, \"M9\", 2) || !strncasecmp(model, \"Leica M9\", 8) || !strncasecmp(model, \"M Monochrom\", 11) || !strncasecmp(model, \"Leica M Monochrom\", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, \"LEICA T\", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, \"LEICA SL\", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); \/\/ Recover tiff-read position!! continue; } if (!strncasecmp(model, \"KODAK P880\", 10) || !strncasecmp(model, \"KODAK P850\", 10) || !strncasecmp(model, \"KODAK P712\", 10)) { if (tag == 0xf90b) { imgdata.makernotes.kodak.clipBlack = get2(); } else if (tag == 0xf90c) { imgdata.makernotes.kodak.clipWhite = get2(); } } if (!strncmp(make, \"Canon\", 5)) { if (tag == 0x000d && len < 256000) \/\/ camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16, len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) \/\/ Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, \"FUJI\", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), \"%s %s\", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, \"%2x\", &c); j += 2) ystr[j \/ 2] = c; ystr[ynum_len \/ 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), \"%s %s %d:%s:%s\", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), \"%s %d:%s:%s %s\", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), \"%s %s %d:%s:%s %s\", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, \"Hasselblad X1D\", 14) || !strncasecmp(model, \"Hasselblad H6D\", 14) || !strncasecmp(model, \"Hasselblad A6D\", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, \"LEICA\", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, \"Leica Camera AG\", 15) && !strncmp(buf, \"LEICA\", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, \"LEICA M\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, \"LEICA S\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, \"NIKON\", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) \/ (float)c; } else if (tag == 0x003b) \/\/ all 1s for regular exposures { imgdata.makernotes.nikon.ME_WB[0] = getreal(type); imgdata.makernotes.nikon.ME_WB[2] = getreal(type); imgdata.makernotes.nikon.ME_WB[1] = getreal(type); imgdata.makernotes.nikon.ME_WB[3] = getreal(type); } else if (tag == 0x0045) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x0082) \/\/ lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) \/\/ lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) \/\/ lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) \/\/ lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 \/ c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops \/ 12.0f; } } else if (tag == 0x0093) \/\/ Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) \/\/ contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: \/\/ encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) \/\/ contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); \/\/ ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } else if (tag == 0x00b9) { uchar uc; int8_t sc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTune = uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneIndex = uc; fread(&sc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneAdj = sc; } } else if (!strncmp(make, \"OLYMPUS\", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) \/ 2); break; case 0x20400612: case 0x30000612: imgdata.sizes.raw_crop.cleft = get2(); break; case 0x20400613: case 0x30000613: imgdata.sizes.raw_crop.ctop = get2(); break; case 0x20400614: case 0x30000614: imgdata.sizes.raw_crop.cwidth = get2(); break; case 0x20400615: case 0x30000615: imgdata.sizes.raw_crop.cheight = get2(); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float)temp; else imgdata.other.CameraTemperature = (float)(temp - 32) \/ 1.8f; if ((OlyID == 0x4434353933ULL) && \/\/ TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || \/\/ E-1 (OlyID == 0x5330303336ULL) || \/\/ E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(make, \"RICOH\", 5)) && !strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { \/\/ sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, \"%02x\", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, \"%8s\", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, \"%02x%02x%02x%02x\", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%02x%02x%02x%02x\", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, \"RICOH\", 5) && strncmp(model, \"PENTAX\", 6)) { if ((tag == 0x0005) && !strncmp(model, \"GXR\", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, \"GXR\", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(model, \"PENTAX\", 6) || (!strncmp(make, \"SAMSUNG\", 7) && dng_version)) && strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x000d) { imgdata.makernotes.pentax.FocusMode = get2(); } else if (tag == 0x000e) { imgdata.makernotes.pentax.AFPointSelected = get2(); } else if (tag == 0x000f) { imgdata.makernotes.pentax.AFPointsInFocus = getint(type); } else if (tag == 0x0010) { imgdata.makernotes.pentax.FocusPosition = get2(); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() \/ 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() \/ 100.0f; } else if (tag == 0x0034) { uchar uc; FORC4 { fread(&uc, 1, 1, ifp); imgdata.makernotes.pentax.DriveMode[c] = uc; } } else if (tag == 0x0038) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); } else if (tag == 0x0039) { imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) \/ 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) \/ 6.0f; } else if (tag == 0x0072) { imgdata.makernotes.pentax.AFAdjustment = get2(); } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) \/\/ Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) \/ sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%d\", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) \/\/ Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, \" \"); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, \"SAMSUNG\", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, \"NX mini\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float)temp; if (get4() == 10) imgdata.other.CameraTemperature \/= 10.0f; } } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() \/ 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, \"SONY\", 4) || !strncasecmp(make, \"Konica\", 6) || !strncasecmp(make, \"Minolta\", 7) || (!strncasecmp(make, \"Hasselblad\", 10) && (!strncasecmp(model, \"Stellar\", 7) || !strncasecmp(model, \"Lunar\", 5) || !strncasecmp(model, \"Lusso\", 5) || !strncasecmp(model, \"HV\", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010, table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400, table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403, table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c, table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, \"NIKON\") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, \"NIKON\") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * libraw_powf64l(2.0f, float(cc) \/ 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64l(2.0, i \/ 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = libraw_powf64l(2.0, i \/ 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = libraw_powf64l(2.0, (short)i \/ -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, \"KONICA\", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, \"Canon\", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 \/* Canon rotation data is handled by EXIF.Orientation *\/ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = \"065\"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, \"Olympus\", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, \"E-410\", 5) || !strncasecmp(model, \"E-510\", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, \"v757-71\")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, \"v757-71\")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200306) { uchar uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.olympus.AFFineTune = uc; } if (tag == 0x20200307) { FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2(); } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, \"NIKON\", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, \"NRW \", 4)) { fseek(ifp, strcmp(buf + 4, \"0100\") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, \"PENTAX\")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, \"D50\"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, \"%d\", serial); #endif } if (tag == 0x29 && type == 1) { \/\/ Canon PowerShot G9 c = wbi < 18 ? \"012347800000005896\"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, \"Samsung\", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { \/\/ shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = \"66666>666;6A;:;55\"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) \/\/ Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) \/\/ Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) \/\/ Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) \/\/ Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD \/\/ not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, \"NIKON\") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { \/* Nikon Capture Note *\/ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 \/ 0x10000; cam_mul[2] = get2() * 382 * 1.173 \/ 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, \"v757-71\")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) \/ 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) \/ 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) \/ 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() \/ 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() \/ 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() \/ 256.0; cam_mul[2] = get2() \/ 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD \/\/ IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) && ((type == 7) || (type == 13)) && !strncasecmp(make, \"Olympus\", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } \/\/ IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, \"OLYMP\", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, \"Samsung\", 7)) { if (tag == 0xa020) \/\/ get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) \/\/ get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } \/* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf (\"Samsung 0xa025 %d\\n\", i); } *\/ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) \/ 256.0; #endif if (tag == 0xa031 && len == 9) \/\/ get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) \/ 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { \/\/ Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; }","output":{"is_vulnerable":"True","vulnerability_types":["Out-of-bounds Write"],"explanation":"There is a stack-based buffer overflow in the parse_makernote function of dcraw_common.cpp in LibRaw 0.19.1. Crafted input will lead to a denial of service or possibly unspecified other impact.","severity_level":"Medium","cwe":"CWE-787","cve":"CVE-2018-20337"}} -{"idx":400895,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if ((length > PNG_UINT_31_MAX) || (length > GetBlobSize(image)) || (count < 4)) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 9) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id >= MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS-1; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { \/* Read global PLTE. *\/ if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (((p-chunk) < (long) length) && *p) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; if (SetImageBackgroundColor(image,exception) == MagickFalse) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || (length % 2) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { if ((MagickSizeType) loop_iters > GetMagickResourceLimit(ListLengthResource)) loop_iters=GetMagickResourceLimit(ListLengthResource); if (loop_iters >= 2147483647L) loop_iters=2147483647L; mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] > 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (((mng_info->magn_methx > 0) && (mng_info->magn_methx <= 5)) && ((mng_info->magn_methy > 0) && (mng_info->magn_methy <= 5))) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { if (prev != (Quantum *) NULL) prev=(Quantum *) RelinquishMagickMemory(prev); if (next != (Quantum *) NULL) next=(Quantum *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (Quantum *) NULL) break; q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers && image->next) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); image=DestroyImageList(image); if (next_image == (Image *) NULL) return((Image *) NULL); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":210449,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char *name, s[2]; const char *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if ((image->storage_class != PseudoClass) && (image->colormap != (PixelInfo *) NULL)) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; if (image->depth != GetImageDepth(image,exception)) (void) SetImageDepth(image,image->depth,exception); for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *r; register Quantum *q; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < MagickMin(image->colors,256); i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { r=GetVirtualPixels(image,0,y,image->columns,1,exception); if (r == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,r) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image,r,opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,r,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image,r,opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,r) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image,r,transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,r); ping_trans_color.green=(unsigned short) GetPixelGreen(image,r); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,r); ping_trans_color.gray=(unsigned short) GetPixelGray(image,r); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,r,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,r,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,r,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,r,semitransparent+i) && GetPixelAlpha(image,r) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image,r,semitransparent+i); } } } r+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } if (number_opaque < 259) { for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != GetPixelGreen(image,r) || GetPixelRed(image,r) != GetPixelBlue(image,r)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != 0 && GetPixelRed(image,r) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,q); SetPixelAlpha(image,TransparentAlpha,q); } else SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR04PixelRGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR03RGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR02PixelBlue(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,q)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,q)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,q)) == 0x00 && GetPixelAlpha(image,q) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } (void) old_bit_depth; image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); \/* write orNT if image->orientation is defined *\/ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); \/* data length=1 *\/ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); \/* PNG uses Exif orientation values *\/ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes+256,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(ping_pixels,0,(rowbytes+256)*sizeof(*ping_pixels)); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) || ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse)) { \/* Palette, Bilevel, or Opaque Monochrome *\/ QuantumType quantum_type; register const Quantum *p; quantum_type=RedQuantum; if (mng_info->IsPalette) { quantum_type=GrayQuantum; if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) quantum_type=IndexQuantum; } SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,ping_pixels,exception); if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"True","vulnerability_types":["Out-of-bounds Write"],"explanation":"A flaw was found in ImageMagick in MagickCore\/quantum-private.h. An attacker who submits a crafted file that is processed by ImageMagick could trigger a heap buffer overflow. This would most likely lead to an impact to application availability, but could potentially lead to an impact to data integrity as well. This flaw affects ImageMagick versions prior to 7.0.9-0.","severity_level":"NoInfo","cwe":"CWE-787","cve":"CVE-2020-27752"}} -{"idx":468323,"input":"WandExport MagickBooleanType MogrifyImageCommand(ImageInfo *image_info, int argc,char **argv,char **wand_unused(metadata),ExceptionInfo *exception) { #define DestroyMogrify() \\ { \\ if (format != (char *) NULL) \\ format=DestroyString(format); \\ if (path != (char *) NULL) \\ path=DestroyString(path); \\ DestroyImageStack(); \\ for (i=0; i < (ssize_t) argc; i++) \\ argv[i]=DestroyString(argv[i]); \\ argv=(char **) RelinquishMagickMemory(argv); \\ } #define ThrowMogrifyException(asperity,tag,option) \\ { \\ (void) ThrowMagickException(exception,GetMagickModule(),asperity,tag,\"`%s'\", \\ option); \\ DestroyMogrify(); \\ return(MagickFalse); \\ } #define ThrowMogrifyInvalidArgumentException(option,argument) \\ { \\ (void) ThrowMagickException(exception,GetMagickModule(),OptionError, \\ \"InvalidArgument\",\"'%s': %s\",argument,option); \\ DestroyMogrify(); \\ return(MagickFalse); \\ } char *format, *option, *path; Image *image; ImageStack image_stack[MaxImageStackDepth+1]; MagickBooleanType global_colormap; MagickBooleanType fire, pend, respect_parenthesis; MagickStatusType status; register ssize_t i; ssize_t j, k; wand_unreferenced(metadata); \/* Set defaults. *\/ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\"); assert(exception != (ExceptionInfo *) NULL); if (argc == 2) { option=argv[1]; if ((LocaleCompare(\"version\",option+1) == 0) || (LocaleCompare(\"-version\",option+1) == 0)) { ListMagickVersion(stdout); return(MagickTrue); } } if (argc < 2) return(MogrifyUsage()); format=(char *) NULL; path=(char *) NULL; global_colormap=MagickFalse; k=0; j=1; NewImageStack(); option=(char *) NULL; pend=MagickFalse; respect_parenthesis=MagickFalse; status=MagickTrue; \/* Parse command line. *\/ ReadCommandlLine(argc,&argv); status=ExpandFilenames(&argc,&argv); if (status == MagickFalse) ThrowMogrifyException(ResourceLimitError,\"MemoryAllocationFailed\", GetExceptionMessage(errno)); for (i=1; i < (ssize_t) argc; i++) { option=argv[i]; if (LocaleCompare(option,\"(\") == 0) { FireImageStack(MagickFalse,MagickTrue,pend); if (k == MaxImageStackDepth) ThrowMogrifyException(OptionError,\"ParenthesisNestedTooDeeply\", option); PushImageStack(); continue; } if (LocaleCompare(option,\")\") == 0) { FireImageStack(MagickFalse,MagickTrue,MagickTrue); if (k == 0) ThrowMogrifyException(OptionError,\"UnableToParseExpression\",option); PopImageStack(); continue; } if (IsCommandOption(option) == MagickFalse) { char backup_filename[MagickPathExtent], *filename; Image *images; struct stat properties; \/* Option is a file name: begin by reading image from specified file. *\/ FireImageStack(MagickFalse,MagickFalse,pend); filename=argv[i]; if ((LocaleCompare(filename,\"--\") == 0) && (i < (ssize_t) (argc-1))) filename=argv[++i]; images=ReadImages(image_info,filename,exception); status&=(images != (Image *) NULL) && (exception->severity < ErrorException); if (images == (Image *) NULL) continue; properties=(*GetBlobProperties(images)); if (format != (char *) NULL) (void) CopyMagickString(images->filename,images->magick_filename, MagickPathExtent); if (path != (char *) NULL) { GetPathComponent(option,TailPath,filename); (void) FormatLocaleString(images->filename,MagickPathExtent, \"%s%c%s\",path,*DirectorySeparator,filename); } if (format != (char *) NULL) AppendImageFormat(format,images->filename); AppendImageStack(images); FinalizeImageSettings(image_info,image,MagickFalse); if (global_colormap != MagickFalse) { QuantizeInfo *quantize_info; quantize_info=AcquireQuantizeInfo(image_info); (void) RemapImages(quantize_info,images,(Image *) NULL,exception); quantize_info=DestroyQuantizeInfo(quantize_info); } *backup_filename='\\0'; if ((LocaleCompare(image->filename,\"-\") != 0) && (IsPathWritable(image->filename) != MagickFalse)) { \/* Rename image file as backup. *\/ (void) CopyMagickString(backup_filename,image->filename, MagickPathExtent); for (j=0; j < 6; j++) { (void) ConcatenateMagickString(backup_filename,\"~\", MagickPathExtent); if (IsPathAccessible(backup_filename) == MagickFalse) break; } if ((IsPathAccessible(backup_filename) != MagickFalse) || (rename_utf8(image->filename,backup_filename) != 0)) *backup_filename='\\0'; } \/* Write transmogrified image to disk. *\/ image_info->synchronize=MagickTrue; status&=WriteImages(image_info,image,image->filename,exception); if (status != MagickFalse) { #if defined(MAGICKCORE_HAVE_UTIME) { MagickBooleanType preserve_timestamp; preserve_timestamp=IsStringTrue(GetImageOption(image_info, \"preserve-timestamp\")); if (preserve_timestamp != MagickFalse) { struct utimbuf timestamp; timestamp.actime=properties.st_atime; timestamp.modtime=properties.st_mtime; (void) utime(image->filename,×tamp); } } #endif if (*backup_filename != '\\0') (void) remove_utf8(backup_filename); } RemoveAllImageStack(); continue; } pend=image != (Image *) NULL ? MagickTrue : MagickFalse; switch (*(option+1)) { case 'a': { if (LocaleCompare(\"adaptive-blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"adaptive-resize\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"adaptive-sharpen\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"affine\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"alpha\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickAlphaChannelOptions,MagickFalse, argv[i]); if (type < 0) ThrowMogrifyException(OptionError, \"UnrecognizedAlphaChannelOption\",argv[i]); break; } if (LocaleCompare(\"annotate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); i++; break; } if (LocaleCompare(\"antialias\",option+1) == 0) break; if (LocaleCompare(\"append\",option+1) == 0) break; if (LocaleCompare(\"attenuate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"authenticate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"auto-gamma\",option+1) == 0) break; if (LocaleCompare(\"auto-level\",option+1) == 0) break; if (LocaleCompare(\"auto-orient\",option+1) == 0) break; if (LocaleCompare(\"auto-threshold\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickAutoThresholdOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError,\"UnrecognizedThresholdMethod\", argv[i]); break; } if (LocaleCompare(\"average\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'b': { if (LocaleCompare(\"background\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"bias\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"black-point-compensation\",option+1) == 0) break; if (LocaleCompare(\"black-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"blue-primary\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"blue-shift\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"border\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"bordercolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"box\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"brightness-contrast\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'c': { if (LocaleCompare(\"cache\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"canny\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"caption\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"channel\",option+1) == 0) { ssize_t channel; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); channel=ParseChannelOption(argv[i]); if (channel < 0) ThrowMogrifyException(OptionError,\"UnrecognizedChannelType\", argv[i]); break; } if (LocaleCompare(\"channel-fx\",option+1) == 0) { ssize_t channel; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); channel=ParsePixelChannelOption(argv[i]); if (channel < 0) ThrowMogrifyException(OptionError,\"UnrecognizedChannelType\", argv[i]); break; } if (LocaleCompare(\"cdl\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"charcoal\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"chop\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"clamp\",option+1) == 0) break; if (LocaleCompare(\"clip\",option+1) == 0) break; if (LocaleCompare(\"clip-mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"clut\",option+1) == 0) break; if (LocaleCompare(\"coalesce\",option+1) == 0) break; if (LocaleCompare(\"colorize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"color-matrix\",option+1) == 0) { KernelInfo *kernel_info; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); kernel_info=AcquireKernelInfo(argv[i],exception); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"colors\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"colorspace\",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedColorspace\", argv[i]); break; } if (LocaleCompare(\"combine\",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedColorspace\", argv[i]); break; } if (LocaleCompare(\"compare\",option+1) == 0) break; if (LocaleCompare(\"comment\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"composite\",option+1) == 0) break; if (LocaleCompare(\"compress\",option+1) == 0) { ssize_t compress; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); compress=ParseCommandOption(MagickCompressOptions,MagickFalse, argv[i]); if (compress < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageCompression\", argv[i]); break; } if (LocaleCompare(\"concurrent\",option+1) == 0) break; if (LocaleCompare(\"connected-components\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"contrast\",option+1) == 0) break; if (LocaleCompare(\"contrast-stretch\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"convolve\",option+1) == 0) { KernelInfo *kernel_info; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); kernel_info=AcquireKernelInfo(argv[i],exception); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"copy\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"crop\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"cycle\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'd': { if (LocaleCompare(\"decipher\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"deconstruct\",option+1) == 0) break; if (LocaleCompare(\"debug\",option+1) == 0) { ssize_t event; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); event=ParseCommandOption(MagickLogEventOptions,MagickFalse,argv[i]); if (event < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEventType\", argv[i]); (void) SetLogEventMask(argv[i]); break; } if (LocaleCompare(\"define\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (*option == '+') { const char *define; define=GetImageOption(image_info,argv[i]); if (define == (const char *) NULL) ThrowMogrifyException(OptionError,\"NoSuchOption\",argv[i]); break; } break; } if (LocaleCompare(\"delay\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"delete\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"density\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"depth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"deskew\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"despeckle\",option+1) == 0) break; if (LocaleCompare(\"dft\",option+1) == 0) break; if (LocaleCompare(\"direction\",option+1) == 0) { ssize_t direction; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, argv[i]); if (direction < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDirectionType\", argv[i]); break; } if (LocaleCompare(\"display\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"dispose\",option+1) == 0) { ssize_t dispose; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, argv[i]); if (dispose < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDisposeMethod\", argv[i]); break; } if (LocaleCompare(\"distort\",option+1) == 0) { ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickDistortOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDistortMethod\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"dither\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickDitherOptions,MagickFalse,argv[i]); if (method < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDitherMethod\", argv[i]); break; } if (LocaleCompare(\"draw\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"duplicate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"duration\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'e': { if (LocaleCompare(\"edge\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"emboss\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"encipher\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"encoding\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"endian\",option+1) == 0) { ssize_t endian; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); endian=ParseCommandOption(MagickEndianOptions,MagickFalse,argv[i]); if (endian < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEndianType\", argv[i]); break; } if (LocaleCompare(\"enhance\",option+1) == 0) break; if (LocaleCompare(\"equalize\",option+1) == 0) break; if (LocaleCompare(\"evaluate\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEvaluateOperator\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"evaluate-sequence\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEvaluateOperator\", argv[i]); break; } if (LocaleCompare(\"extent\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"extract\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'f': { if (LocaleCompare(\"family\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"features\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"fill\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"filter\",option+1) == 0) { ssize_t filter; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); filter=ParseCommandOption(MagickFilterOptions,MagickFalse,argv[i]); if (filter < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageFilter\", argv[i]); break; } if (LocaleCompare(\"flatten\",option+1) == 0) break; if (LocaleCompare(\"flip\",option+1) == 0) break; if (LocaleCompare(\"flop\",option+1) == 0) break; if (LocaleCompare(\"floodfill\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"font\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"format\",option+1) == 0) { (void) CopyMagickString(argv[i]+1,\"sans\",MagickPathExtent); (void) CloneString(&format,(char *) NULL); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); (void) CloneString(&format,argv[i]); (void) CopyMagickString(image_info->filename,format, MagickPathExtent); (void) ConcatenateMagickString(image_info->filename,\":\", MagickPathExtent); (void) SetImageInfo(image_info,0,exception); if (*image_info->magick == '\\0') ThrowMogrifyException(OptionError,\"UnrecognizedImageFormat\", format); break; } if (LocaleCompare(\"frame\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"function\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickFunctionOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedFunction\",argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"fuzz\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"fx\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'g': { if (LocaleCompare(\"gamma\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if ((LocaleCompare(\"gaussian-blur\",option+1) == 0) || (LocaleCompare(\"gaussian\",option+1) == 0)) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"geometry\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"gravity\",option+1) == 0) { ssize_t gravity; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse, argv[i]); if (gravity < 0) ThrowMogrifyException(OptionError,\"UnrecognizedGravityType\", argv[i]); break; } if (LocaleCompare(\"grayscale\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickPixelIntensityOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError,\"UnrecognizedIntensityMethod\", argv[i]); break; } if (LocaleCompare(\"green-primary\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'h': { if (LocaleCompare(\"hald-clut\",option+1) == 0) break; if ((LocaleCompare(\"help\",option+1) == 0) || (LocaleCompare(\"-help\",option+1) == 0)) return(MogrifyUsage()); if (LocaleCompare(\"hough-lines\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'i': { if (LocaleCompare(\"identify\",option+1) == 0) break; if (LocaleCompare(\"idft\",option+1) == 0) break; if (LocaleCompare(\"implode\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"intensity\",option+1) == 0) { ssize_t intensity; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,argv[i]); if (intensity < 0) ThrowMogrifyException(OptionError, \"UnrecognizedPixelIntensityMethod\",argv[i]); break; } if (LocaleCompare(\"intent\",option+1) == 0) { ssize_t intent; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); intent=ParseCommandOption(MagickIntentOptions,MagickFalse,argv[i]); if (intent < 0) ThrowMogrifyException(OptionError,\"UnrecognizedIntentType\", argv[i]); break; } if (LocaleCompare(\"interlace\",option+1) == 0) { ssize_t interlace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); interlace=ParseCommandOption(MagickInterlaceOptions,MagickFalse, argv[i]); if (interlace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedInterlaceType\", argv[i]); break; } if (LocaleCompare(\"interline-spacing\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"interpolate\",option+1) == 0) { ssize_t interpolate; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse, argv[i]); if (interpolate < 0) ThrowMogrifyException(OptionError,\"UnrecognizedInterpolateMethod\", argv[i]); break; } if (LocaleCompare(\"interword-spacing\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'k': { if (LocaleCompare(\"kerning\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"kuwahara\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'l': { if (LocaleCompare(\"label\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"lat\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); } if (LocaleCompare(\"layers\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickLayerOptions,MagickFalse,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedLayerMethod\", argv[i]); break; } if (LocaleCompare(\"level\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"level-colors\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"limit\",option+1) == 0) { char *p; double value; ssize_t resource; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); resource=ParseCommandOption(MagickResourceOptions,MagickFalse, argv[i]); if (resource < 0) ThrowMogrifyException(OptionError,\"UnrecognizedResourceType\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); value=StringToDouble(argv[i],&p); (void) value; if ((p == argv[i]) && (LocaleCompare(\"unlimited\",argv[i]) != 0)) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"liquid-rescale\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"list\",option+1) == 0) { ssize_t list; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); list=ParseCommandOption(MagickListOptions,MagickFalse,argv[i]); if (list < 0) ThrowMogrifyException(OptionError,\"UnrecognizedListType\",argv[i]); status=MogrifyImageInfo(image_info,(int) (i-j+1),(const char **) argv+j,exception); return(status == 0 ? MagickTrue : MagickFalse); } if (LocaleCompare(\"log\",option+1) == 0) { if (*option == '+') break; i++; if ((i == (ssize_t) argc) || (strchr(argv[i],'%') == (char *) NULL)) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"loop\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'm': { if (LocaleCompare(\"map\",option+1) == 0) { global_colormap=(*option == '+') ? MagickTrue : MagickFalse; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"matte\",option+1) == 0) break; if (LocaleCompare(\"mattecolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"maximum\",option+1) == 0) break; if (LocaleCompare(\"mean-shift\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"median\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"metric\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickMetricOptions,MagickTrue,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedMetricType\", argv[i]); break; } if (LocaleCompare(\"minimum\",option+1) == 0) break; if (LocaleCompare(\"modulate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"mode\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"monitor\",option+1) == 0) break; if (LocaleCompare(\"monochrome\",option+1) == 0) break; if (LocaleCompare(\"morph\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"morphology\",option+1) == 0) { char token[MagickPathExtent]; KernelInfo *kernel_info; ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); GetNextToken(argv[i],(const char **) NULL,MagickPathExtent,token); op=ParseCommandOption(MagickMorphologyOptions,MagickFalse,token); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedMorphologyMethod\", token); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); kernel_info=AcquireKernelInfo(argv[i],exception); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"mosaic\",option+1) == 0) break; if (LocaleCompare(\"motion-blur\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'n': { if (LocaleCompare(\"negate\",option+1) == 0) break; if (LocaleCompare(\"noise\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (*option == '+') { ssize_t noise; noise=ParseCommandOption(MagickNoiseOptions,MagickFalse, argv[i]); if (noise < 0) ThrowMogrifyException(OptionError,\"UnrecognizedNoiseType\", argv[i]); break; } if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"noop\",option+1) == 0) break; if (LocaleCompare(\"normalize\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'o': { if (LocaleCompare(\"opaque\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"ordered-dither\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"orient\",option+1) == 0) { ssize_t orientation; orientation=UndefinedOrientation; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); orientation=ParseCommandOption(MagickOrientationOptions,MagickFalse, argv[i]); if (orientation < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageOrientation\", argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'p': { if (LocaleCompare(\"page\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"paint\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"path\",option+1) == 0) { (void) CloneString(&path,(char *) NULL); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); (void) CloneString(&path,argv[i]); break; } if (LocaleCompare(\"perceptible\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"pointsize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"polaroid\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"poly\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"posterize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"precision\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"print\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"process\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"profile\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'q': { if (LocaleCompare(\"quality\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"quantize\",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedColorspace\", argv[i]); break; } if (LocaleCompare(\"quiet\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'r': { if (LocaleCompare(\"rotational-blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"raise\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"random-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"read-mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"red-primary\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); } if (LocaleCompare(\"regard-warnings\",option+1) == 0) break; if (LocaleCompare(\"region\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"remap\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"render\",option+1) == 0) break; if (LocaleCompare(\"repage\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"resample\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"resize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleNCompare(\"respect-parentheses\",option+1,17) == 0) { respect_parenthesis=(*option == '-') ? MagickTrue : MagickFalse; break; } if (LocaleCompare(\"reverse\",option+1) == 0) break; if (LocaleCompare(\"roll\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"rotate\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 's': { if (LocaleCompare(\"sample\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sampling-factor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"scale\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"scene\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"seed\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"segment\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"selective-blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"separate\",option+1) == 0) break; if (LocaleCompare(\"sepia-tone\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"set\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"shade\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"shadow\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sharpen\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"shave\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"shear\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sigmoidal-contrast\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"size\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sketch\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"smush\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; break; } if (LocaleCompare(\"solarize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sparse-color\",option+1) == 0) { ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickSparseColorOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedSparseColorMethod\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"splice\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"spread\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"statistic\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickStatisticOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedStatisticType\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"stretch\",option+1) == 0) { ssize_t stretch; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse, argv[i]); if (stretch < 0) ThrowMogrifyException(OptionError,\"UnrecognizedStyleType\", argv[i]); break; } if (LocaleCompare(\"strip\",option+1) == 0) break; if (LocaleCompare(\"stroke\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"strokewidth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"style\",option+1) == 0) { ssize_t style; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); style=ParseCommandOption(MagickStyleOptions,MagickFalse,argv[i]); if (style < 0) ThrowMogrifyException(OptionError,\"UnrecognizedStyleType\", argv[i]); break; } if (LocaleCompare(\"swap\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"swirl\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"synchronize\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 't': { if (LocaleCompare(\"taint\",option+1) == 0) break; if (LocaleCompare(\"texture\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"tile\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"tile-offset\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"tint\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"transform\",option+1) == 0) break; if (LocaleCompare(\"transpose\",option+1) == 0) break; if (LocaleCompare(\"transverse\",option+1) == 0) break; if (LocaleCompare(\"threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"thumbnail\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"transparent\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"transparent-color\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"treedepth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"trim\",option+1) == 0) break; if (LocaleCompare(\"type\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickTypeOptions,MagickFalse,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageType\", argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'u': { if (LocaleCompare(\"undercolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"unique-colors\",option+1) == 0) break; if (LocaleCompare(\"units\",option+1) == 0) { ssize_t units; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); units=ParseCommandOption(MagickResolutionOptions,MagickFalse, argv[i]); if (units < 0) ThrowMogrifyException(OptionError,\"UnrecognizedUnitsType\", argv[i]); break; } if (LocaleCompare(\"unsharp\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'v': { if (LocaleCompare(\"verbose\",option+1) == 0) { image_info->verbose=(*option == '-') ? MagickTrue : MagickFalse; break; } if ((LocaleCompare(\"version\",option+1) == 0) || (LocaleCompare(\"-version\",option+1) == 0)) { ListMagickVersion(stdout); break; } if (LocaleCompare(\"vignette\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"virtual-pixel\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickVirtualPixelOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError, \"UnrecognizedVirtualPixelMethod\",argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'w': { if (LocaleCompare(\"wave\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"wavelet-denoise\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"weight\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"white-point\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"white-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"write\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"write-mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case '?': break; default: ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } fire=(GetCommandOptionFlags(MagickCommandOptions,MagickFalse,option) & FireOptionFlag) == 0 ? MagickFalse : MagickTrue; if (fire != MagickFalse) FireImageStack(MagickFalse,MagickTrue,MagickTrue); } if (k != 0) ThrowMogrifyException(OptionError,\"UnbalancedParenthesis\",argv[i]); if (i != (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingAnImageFilename\",argv[i]); DestroyMogrify(); return(status != 0 ? MagickTrue : MagickFalse); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":200950,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MaxTextExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False when converting or mogrifying *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; \/* Skip nominal layer count, frame count, and play time *\/ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\", \"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, \"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); mng_info=MngInfoFreeStruct(mng_info); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (((p-chunk) < (long) length) && *p) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters \", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(png_uint_32) p[12] << 8) & png_uint_32) p[13]; else basi_red=0; if (length > 15) basi_green=(png_uint_32) p[14] << 8) & png_uint_32) p[15]; else basi_green=0; if (length > 17) basi_blue=(png_uint_32) p[16] << 8) & png_uint_32) p[17]; else basi_blue=0; if (length > 19) basi_alpha=(png_uint_32) p[18] << 8) & png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { if (prev != (PixelPacket *) NULL) prev=(PixelPacket *) RelinquishMagickMemory(prev); if (next != (PixelPacket *) NULL) next=(PixelPacket *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (PixelPacket *) NULL) break; q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { \/* Interpolate *\/ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))\/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ else { \/* Interpolate *\/ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage();\"); return(image); }","output":{"is_vulnerable":"True","vulnerability_types":["Loop with Unreachable Exit Condition ('Infinite Loop')"],"explanation":"In ImageMagick 7.0.7-28, there is an infinite loop in the ReadOneMNGImage function of the coders\/png.c file. Remote attackers could leverage this vulnerability to cause a denial of service via a crafted mng file.","severity_level":"Medium","cwe":"CWE-835","cve":"CVE-2018-10177"}} -{"idx":81049,"input":"WandExport MagickBooleanType MogrifyImage(ImageInfo *image_info,const int argc, const char **argv,Image **image,ExceptionInfo *exception) { ChannelType channel; const char *format, *option; DrawInfo *draw_info; GeometryInfo geometry_info; Image *region_image; ImageInfo *mogrify_info; MagickStatusType status; MagickPixelPacket fill; MagickStatusType flags; QuantizeInfo *quantize_info; RectangleInfo geometry, region_geometry; register ssize_t i; \/* Initialize method variables. *\/ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image **) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",(*image)->filename); if (argc < 0) return(MagickTrue); mogrify_info=CloneImageInfo(image_info); draw_info=CloneDrawInfo(mogrify_info,(DrawInfo *) NULL); quantize_info=AcquireQuantizeInfo(mogrify_info); SetGeometryInfo(&geometry_info); GetMagickPixelPacket(*image,&fill); SetMagickPixelPacket(*image,&(*image)->background_color,(IndexPacket *) NULL, &fill); channel=mogrify_info->channel; format=GetImageOption(mogrify_info,\"format\"); SetGeometry(*image,®ion_geometry); region_image=NewImageList(); \/* Transmogrify the image. *\/ for (i=0; i < (ssize_t) argc; i++) { Image *mogrify_image; ssize_t count; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=MagickMax(ParseCommandOption(MagickCommandOptions,MagickFalse,option), 0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); mogrify_image=(Image *) NULL; switch (*(option+1)) { case 'a': { if (LocaleCompare(\"adaptive-blur\",option+1) == 0) { \/* Adaptive blur image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=AdaptiveBlurImageChannel(*image,channel, geometry_info.rho,geometry_info.sigma,exception); break; } if (LocaleCompare(\"adaptive-resize\",option+1) == 0) { \/* Adaptive resize image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=AdaptiveResizeImage(*image,geometry.width, geometry.height,exception); break; } if (LocaleCompare(\"adaptive-sharpen\",option+1) == 0) { \/* Adaptive sharpen image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=AdaptiveSharpenImageChannel(*image,channel, geometry_info.rho,geometry_info.sigma,exception); break; } if (LocaleCompare(\"affine\",option+1) == 0) { \/* Affine matrix. *\/ if (*option == '+') { GetAffineMatrix(&draw_info->affine); break; } (void) ParseAffineGeometry(argv[i+1],&draw_info->affine,exception); break; } if (LocaleCompare(\"alpha\",option+1) == 0) { AlphaChannelType alpha_type; (void) SyncImageSettings(mogrify_info,*image); alpha_type=(AlphaChannelType) ParseCommandOption(MagickAlphaOptions, MagickFalse,argv[i+1]); (void) SetImageAlphaChannel(*image,alpha_type); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"annotate\",option+1) == 0) { char *text, geometry[MaxTextExtent]; \/* Annotate image. *\/ (void) SyncImageSettings(mogrify_info,*image); SetGeometryInfo(&geometry_info); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; text=InterpretImageProperties(mogrify_info,*image,argv[i+2]); InheritException(exception,&(*image)->exception); if (text == (char *) NULL) break; (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,\"%+f%+f\", geometry_info.xi,geometry_info.psi); (void) CloneString(&draw_info->geometry,geometry); draw_info->affine.sx=cos(DegreesToRadians( fmod(geometry_info.rho,360.0))); draw_info->affine.rx=sin(DegreesToRadians( fmod(geometry_info.rho,360.0))); draw_info->affine.ry=(-sin(DegreesToRadians( fmod(geometry_info.sigma,360.0)))); draw_info->affine.sy=cos(DegreesToRadians( fmod(geometry_info.sigma,360.0))); (void) AnnotateImage(*image,draw_info); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"antialias\",option+1) == 0) { draw_info->stroke_antialias=(*option == '-') ? MagickTrue : MagickFalse; draw_info->text_antialias=(*option == '-') ? MagickTrue : MagickFalse; break; } if (LocaleCompare(\"auto-gamma\",option+1) == 0) { \/* Auto Adjust Gamma of image based on its mean *\/ (void) SyncImageSettings(mogrify_info,*image); (void) AutoGammaImageChannel(*image,channel); break; } if (LocaleCompare(\"auto-level\",option+1) == 0) { \/* Perfectly Normalize (max\/min stretch) the image *\/ (void) SyncImageSettings(mogrify_info,*image); (void) AutoLevelImageChannel(*image,channel); break; } if (LocaleCompare(\"auto-orient\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); mogrify_image=AutoOrientImage(*image,(*image)->orientation, exception); break; } break; } case 'b': { if (LocaleCompare(\"black-threshold\",option+1) == 0) { \/* Black threshold image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) BlackThresholdImageChannel(*image,channel,argv[i+1], exception); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"blue-shift\",option+1) == 0) { \/* Blue shift image. *\/ (void) SyncImageSettings(mogrify_info,*image); geometry_info.rho=1.5; if (*option == '-') flags=ParseGeometry(argv[i+1],&geometry_info); mogrify_image=BlueShiftImage(*image,geometry_info.rho,exception); break; } if (LocaleCompare(\"blur\",option+1) == 0) { \/* Gaussian blur image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=BlurImageChannel(*image,channel,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"border\",option+1) == 0) { \/* Surround image with a border of solid color. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=BorderImage(*image,&geometry,exception); break; } if (LocaleCompare(\"bordercolor\",option+1) == 0) { if (*option == '+') { (void) QueryColorDatabase(MogrifyBorderColor, &draw_info->border_color,exception); break; } (void) QueryColorDatabase(argv[i+1],&draw_info->border_color, exception); break; } if (LocaleCompare(\"box\",option+1) == 0) { (void) QueryColorDatabase(argv[i+1],&draw_info->undercolor, exception); break; } if (LocaleCompare(\"brightness-contrast\",option+1) == 0) { double brightness, contrast; GeometryInfo geometry_info; MagickStatusType flags; \/* Brightness \/ contrast image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); brightness=geometry_info.rho; contrast=0.0; if ((flags & SigmaValue) != 0) contrast=geometry_info.sigma; (void) BrightnessContrastImageChannel(*image,channel,brightness, contrast); InheritException(exception,&(*image)->exception); break; } break; } case 'c': { if (LocaleCompare(\"canny\",option+1) == 0) { \/* Detect edges in the image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=0.10; if ((flags & PsiValue) == 0) geometry_info.psi=0.30; if ((flags & PercentValue) != 0) { geometry_info.xi\/=100.0; geometry_info.psi\/=100.0; } mogrify_image=CannyEdgeImage(*image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,geometry_info.psi,exception); break; } if (LocaleCompare(\"cdl\",option+1) == 0) { char *color_correction_collection; \/* Color correct with a color decision list. *\/ (void) SyncImageSettings(mogrify_info,*image); color_correction_collection=FileToString(argv[i+1],~0UL,exception); if (color_correction_collection == (char *) NULL) break; (void) ColorDecisionListImage(*image,color_correction_collection); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"channel\",option+1) == 0) { if (*option == '+') channel=DefaultChannels; else channel=(ChannelType) ParseChannelOption(argv[i+1]); break; } if (LocaleCompare(\"charcoal\",option+1) == 0) { \/* Charcoal image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=CharcoalImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"chop\",option+1) == 0) { \/* Chop the image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseGravityGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ChopImage(*image,&geometry,exception); break; } if (LocaleCompare(\"clamp\",option+1) == 0) { \/* Clamp image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ClampImageChannel(*image,channel); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"clip\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') { (void) SetImageClipMask(*image,(Image *) NULL); InheritException(exception,&(*image)->exception); break; } (void) ClipImage(*image); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"clip-mask\",option+1) == 0) { CacheView *mask_view; Image *mask_image; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t y; (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') { \/* Remove a mask. *\/ (void) SetImageMask(*image,(Image *) NULL); InheritException(exception,&(*image)->exception); break; } \/* Set the image mask. FUTURE: This Should Be a SetImageAlphaChannel() call, Or two. *\/ mask_image=GetImageCache(mogrify_info,argv[i+1],exception); if (mask_image == (Image *) NULL) break; if (SetImageStorageClass(mask_image,DirectClass) == MagickFalse) return(MagickFalse); mask_view=AcquireAuthenticCacheView(mask_image,exception); for (y=0; y < (ssize_t) mask_image->rows; y++) { q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) mask_image->columns; x++) { if (mask_image->matte == MagickFalse) SetPixelOpacity(q,ClampToQuantum(GetPixelIntensity(mask_image, q))); SetPixelRed(q,GetPixelOpacity(q)); SetPixelGreen(q,GetPixelOpacity(q)); SetPixelBlue(q,GetPixelOpacity(q)); q++; } if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse) break; } mask_view=DestroyCacheView(mask_view); mask_image->matte=MagickTrue; (void) SetImageClipMask(*image,mask_image); mask_image=DestroyImage(mask_image); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"clip-path\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); (void) ClipImagePath(*image,argv[i+1],*option == '-' ? MagickTrue : MagickFalse); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"colorize\",option+1) == 0) { \/* Colorize the image. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=ColorizeImage(*image,argv[i+1],draw_info->fill, exception); break; } if (LocaleCompare(\"color-matrix\",option+1) == 0) { KernelInfo *kernel; (void) SyncImageSettings(mogrify_info,*image); kernel=AcquireKernelInfo(argv[i+1]); if (kernel == (KernelInfo *) NULL) break; mogrify_image=ColorMatrixImage(*image,kernel,exception); kernel=DestroyKernelInfo(kernel); break; } if (LocaleCompare(\"colors\",option+1) == 0) { \/* Reduce the number of colors in the image. *\/ (void) SyncImageSettings(mogrify_info,*image); quantize_info->number_colors=StringToUnsignedLong(argv[i+1]); if (quantize_info->number_colors == 0) break; if (((*image)->storage_class == DirectClass) || (*image)->colors > quantize_info->number_colors) (void) QuantizeImage(quantize_info,*image); else (void) CompressImageColormap(*image); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"colorspace\",option+1) == 0) { ColorspaceType colorspace; (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') { (void) TransformImageColorspace(*image,sRGBColorspace); InheritException(exception,&(*image)->exception); break; } colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); (void) TransformImageColorspace(*image,colorspace); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"connected-components\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); mogrify_image=ConnectedComponentsImage(*image, StringToInteger(argv[i+1]),exception); break; } if (LocaleCompare(\"contrast\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); (void) ContrastImage(*image,(*option == '-') ? MagickTrue : MagickFalse); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"contrast-stretch\",option+1) == 0) { double black_point, white_point; MagickStatusType flags; \/* Contrast stretch image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); black_point=geometry_info.rho; white_point=(flags & SigmaValue) != 0 ? geometry_info.sigma : black_point; if ((flags & PercentValue) != 0) { black_point*=(double) (*image)->columns*(*image)->rows\/100.0; white_point*=(double) (*image)->columns*(*image)->rows\/100.0; } white_point=(MagickRealType) (*image)->columns*(*image)->rows- white_point; (void) ContrastStretchImageChannel(*image,channel,black_point, white_point); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"convolve\",option+1) == 0) { double gamma; KernelInfo *kernel_info; register ssize_t j; size_t extent; (void) SyncImageSettings(mogrify_info,*image); kernel_info=AcquireKernelInfo(argv[i+1]); if (kernel_info == (KernelInfo *) NULL) break; extent=kernel_info->width*kernel_info->height; gamma=0.0; for (j=0; j < (ssize_t) extent; j++) gamma+=kernel_info->values[j]; gamma=1.0\/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma); for (j=0; j < (ssize_t) extent; j++) kernel_info->values[j]*=gamma; mogrify_image=MorphologyImage(*image,CorrelateMorphology,1, kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"crop\",option+1) == 0) { \/* Crop a image to a smaller size *\/ (void) SyncImageSettings(mogrify_info,*image); #if 0 flags=ParseGravityGeometry(*image,argv[i+1],&geometry,exception); if (((geometry.width != 0) || (geometry.height != 0)) && ((flags & XValue) == 0) && ((flags & YValue) == 0)) break; #endif #if 0 mogrify_image=CloneImage(*image,0,0,MagickTrue,&(*image)->exception); mogrify_image->next = mogrify_image->previous = (Image *) NULL; (void) TransformImage(&mogrify_image,argv[i+1],(char *) NULL); InheritException(exception,&mogrify_image->exception); #else mogrify_image=CropImageToTiles(*image,argv[i+1],exception); #endif break; } if (LocaleCompare(\"cycle\",option+1) == 0) { \/* Cycle an image colormap. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) CycleColormapImage(*image,(ssize_t) StringToLong(argv[i+1])); InheritException(exception,&(*image)->exception); break; } break; } case 'd': { if (LocaleCompare(\"decipher\",option+1) == 0) { StringInfo *passkey; \/* Decipher pixels. *\/ (void) SyncImageSettings(mogrify_info,*image); passkey=FileToStringInfo(argv[i+1],~0UL,exception); if (passkey != (StringInfo *) NULL) { (void) PasskeyDecipherImage(*image,passkey,exception); passkey=DestroyStringInfo(passkey); } break; } if (LocaleCompare(\"density\",option+1) == 0) { \/* Set image density. *\/ (void) CloneString(&draw_info->density,argv[i+1]); break; } if (LocaleCompare(\"depth\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') { (void) SetImageDepth(*image,MAGICKCORE_QUANTUM_DEPTH); break; } (void) SetImageDepth(*image,StringToUnsignedLong(argv[i+1])); break; } if (LocaleCompare(\"deskew\",option+1) == 0) { double threshold; \/* Straighten the image. *\/ (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') threshold=40.0*QuantumRange\/100.0; else threshold=StringToDoubleInterval(argv[i+1],(double) QuantumRange+ 1.0); mogrify_image=DeskewImage(*image,threshold,exception); break; } if (LocaleCompare(\"despeckle\",option+1) == 0) { \/* Reduce the speckles within an image. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=DespeckleImage(*image,exception); break; } if (LocaleCompare(\"display\",option+1) == 0) { (void) CloneString(&draw_info->server_name,argv[i+1]); break; } if (LocaleCompare(\"distort\",option+1) == 0) { char *args, token[MaxTextExtent]; const char *p; DistortImageMethod method; double *arguments; register ssize_t x; size_t number_arguments; \/* Distort image. *\/ (void) SyncImageSettings(mogrify_info,*image); method=(DistortImageMethod) ParseCommandOption(MagickDistortOptions, MagickFalse,argv[i+1]); if (method == ResizeDistortion) { double resize_args[2]; \/* Resize distortion. *\/ (void) ParseRegionGeometry(*image,argv[i+2],&geometry, exception); resize_args[0]=(double) geometry.width; resize_args[1]=(double) geometry.height; mogrify_image=DistortImage(*image,method,(size_t) 2, resize_args,MagickTrue,exception); break; } args=InterpretImageProperties(mogrify_info,*image,argv[i+2]); InheritException(exception,&(*image)->exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\\0'; x++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, \"MemoryAllocationFailed\",(*image)->filename); (void) memset(arguments,0,number_arguments*sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\\0'); x++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); mogrify_image=DistortImage(*image,method,number_arguments,arguments, (*option == '+') ? MagickTrue : MagickFalse,exception); arguments=(double *) RelinquishMagickMemory(arguments); break; } if (LocaleCompare(\"dither\",option+1) == 0) { if (*option == '+') { quantize_info->dither=MagickFalse; break; } quantize_info->dither=MagickTrue; quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); if (quantize_info->dither_method == NoDitherMethod) quantize_info->dither=MagickFalse; break; } if (LocaleCompare(\"draw\",option+1) == 0) { \/* Draw image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) CloneString(&draw_info->primitive,argv[i+1]); (void) DrawImage(*image,draw_info); InheritException(exception,&(*image)->exception); break; } break; } case 'e': { if (LocaleCompare(\"edge\",option+1) == 0) { \/* Enhance edges in the image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=EdgeImage(*image,geometry_info.rho,exception); break; } if (LocaleCompare(\"emboss\",option+1) == 0) { \/* Gaussian embossen image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=EmbossImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"encipher\",option+1) == 0) { StringInfo *passkey; \/* Encipher pixels. *\/ (void) SyncImageSettings(mogrify_info,*image); passkey=FileToStringInfo(argv[i+1],~0UL,exception); if (passkey != (StringInfo *) NULL) { (void) PasskeyEncipherImage(*image,passkey,exception); passkey=DestroyStringInfo(passkey); } break; } if (LocaleCompare(\"encoding\",option+1) == 0) { (void) CloneString(&draw_info->encoding,argv[i+1]); break; } if (LocaleCompare(\"enhance\",option+1) == 0) { \/* Enhance image. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=EnhanceImage(*image,exception); break; } if (LocaleCompare(\"equalize\",option+1) == 0) { \/* Equalize image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) EqualizeImageChannel(*image,channel); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"evaluate\",option+1) == 0) { double constant; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*image); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); constant=StringToDoubleInterval(argv[i+2],(double) QuantumRange+ 1.0); (void) EvaluateImageChannel(*image,channel,op,constant,exception); break; } if (LocaleCompare(\"extent\",option+1) == 0) { \/* Set the image extent. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGravityGeometry(*image,argv[i+1],&geometry,exception); if (geometry.width == 0) geometry.width=(*image)->columns; if (geometry.height == 0) geometry.height=(*image)->rows; mogrify_image=ExtentImage(*image,&geometry,exception); break; } break; } case 'f': { if (LocaleCompare(\"family\",option+1) == 0) { if (*option == '+') { if (draw_info->family != (char *) NULL) draw_info->family=DestroyString(draw_info->family); break; } (void) CloneString(&draw_info->family,argv[i+1]); break; } if (LocaleCompare(\"features\",option+1) == 0) { if (*option == '+') { (void) DeleteImageArtifact(*image,\"identify:features\"); break; } (void) SetImageArtifact(*image,\"identify:features\",argv[i+1]); (void) SetImageArtifact(*image,\"verbose\",\"true\"); break; } if (LocaleCompare(\"fill\",option+1) == 0) { ExceptionInfo *sans; GetMagickPixelPacket(*image,&fill); if (*option == '+') { (void) QueryMagickColor(\"none\",&fill,exception); (void) QueryColorDatabase(\"none\",&draw_info->fill,exception); if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); break; } sans=AcquireExceptionInfo(); (void) QueryMagickColor(argv[i+1],&fill,sans); status=QueryColorDatabase(argv[i+1],&draw_info->fill,sans); sans=DestroyExceptionInfo(sans); if (status == MagickFalse) draw_info->fill_pattern=GetImageCache(mogrify_info,argv[i+1], exception); break; } if (LocaleCompare(\"flip\",option+1) == 0) { \/* Flip image scanlines. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=FlipImage(*image,exception); break; } if (LocaleCompare(\"floodfill\",option+1) == 0) { MagickPixelPacket target; \/* Floodfill image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParsePageGeometry(*image,argv[i+1],&geometry,exception); (void) QueryMagickColor(argv[i+2],&target,exception); (void) FloodfillPaintImage(*image,channel,draw_info,&target, geometry.x,geometry.y,*option == '-' ? MagickFalse : MagickTrue); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"flop\",option+1) == 0) { \/* Flop image scanlines. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=FlopImage(*image,exception); break; } if (LocaleCompare(\"font\",option+1) == 0) { if (*option == '+') { if (draw_info->font != (char *) NULL) draw_info->font=DestroyString(draw_info->font); break; } (void) CloneString(&draw_info->font,argv[i+1]); break; } if (LocaleCompare(\"format\",option+1) == 0) { format=argv[i+1]; break; } if (LocaleCompare(\"frame\",option+1) == 0) { FrameInfo frame_info; \/* Surround image with an ornamental border. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); frame_info.width=geometry.width; frame_info.height=geometry.height; frame_info.outer_bevel=geometry.x; frame_info.inner_bevel=geometry.y; frame_info.x=(ssize_t) frame_info.width; frame_info.y=(ssize_t) frame_info.height; frame_info.width=(*image)->columns+2*frame_info.width; frame_info.height=(*image)->rows+2*frame_info.height; mogrify_image=FrameImage(*image,&frame_info,exception); break; } if (LocaleCompare(\"function\",option+1) == 0) { char *arguments, token[MaxTextExtent]; const char *p; double *parameters; MagickFunction function; register ssize_t x; size_t number_parameters; \/* Function Modify Image Values *\/ (void) SyncImageSettings(mogrify_info,*image); function=(MagickFunction) ParseCommandOption(MagickFunctionOptions, MagickFalse,argv[i+1]); arguments=InterpretImageProperties(mogrify_info,*image,argv[i+2]); InheritException(exception,&(*image)->exception); if (arguments == (char *) NULL) break; p=(char *) arguments; for (x=0; *p != '\\0'; x++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); } number_parameters=(size_t) x; parameters=(double *) AcquireQuantumMemory(number_parameters, sizeof(*parameters)); if (parameters == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, \"MemoryAllocationFailed\",(*image)->filename); (void) memset(parameters,0,number_parameters* sizeof(*parameters)); p=(char *) arguments; for (x=0; (x < (ssize_t) number_parameters) && (*p != '\\0'); x++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); parameters[x]=StringToDouble(token,(char **) NULL); } arguments=DestroyString(arguments); (void) FunctionImageChannel(*image,channel,function, number_parameters,parameters,exception); parameters=(double *) RelinquishMagickMemory(parameters); break; } break; } case 'g': { if (LocaleCompare(\"gamma\",option+1) == 0) { \/* Gamma image. *\/ (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') (*image)->gamma=StringToDouble(argv[i+1],(char **) NULL); else { if (strchr(argv[i+1],',') != (char *) NULL) (void) GammaImage(*image,argv[i+1]); else (void) GammaImageChannel(*image,channel, StringToDouble(argv[i+1],(char **) NULL)); InheritException(exception,&(*image)->exception); } break; } if ((LocaleCompare(\"gaussian-blur\",option+1) == 0) || (LocaleCompare(\"gaussian\",option+1) == 0)) { \/* Gaussian blur image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=GaussianBlurImageChannel(*image,channel, geometry_info.rho,geometry_info.sigma,exception); break; } if (LocaleCompare(\"geometry\",option+1) == 0) { \/* Record Image offset, Resize last image. *\/ (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') { if ((*image)->geometry != (char *) NULL) (*image)->geometry=DestroyString((*image)->geometry); break; } flags=ParseRegionGeometry(*image,argv[i+1],&geometry,exception); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) (void) CloneString(&(*image)->geometry,argv[i+1]); else mogrify_image=ResizeImage(*image,geometry.width,geometry.height, (*image)->filter,(*image)->blur,exception); break; } if (LocaleCompare(\"gravity\",option+1) == 0) { if (*option == '+') { draw_info->gravity=UndefinedGravity; break; } draw_info->gravity=(GravityType) ParseCommandOption( MagickGravityOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"grayscale\",option+1) == 0) { PixelIntensityMethod method; (void) SyncImagesSettings(mogrify_info,*image); method=(PixelIntensityMethod) ParseCommandOption( MagickPixelIntensityOptions,MagickFalse,argv[i+1]); (void) GrayscaleImage(*image,method); InheritException(exception,&(*image)->exception); break; } break; } case 'h': { if (LocaleCompare(\"highlight-color\",option+1) == 0) { (void) SetImageArtifact(*image,\"compare:highlight-color\",argv[i+1]); break; } if (LocaleCompare(\"hough-lines\",option+1) == 0) { \/* Identify lines in the image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if ((flags & XiValue) == 0) geometry_info.xi=40; mogrify_image=HoughLineImage(*image,(size_t) geometry_info.rho, (size_t) geometry_info.sigma,(size_t) geometry_info.xi,exception); break; } break; } case 'i': { if (LocaleCompare(\"identify\",option+1) == 0) { char *text; (void) SyncImageSettings(mogrify_info,*image); if (format == (char *) NULL) { (void) IdentifyImage(*image,stdout,mogrify_info->verbose); InheritException(exception,&(*image)->exception); break; } text=InterpretImageProperties(mogrify_info,*image,format); InheritException(exception,&(*image)->exception); if (text == (char *) NULL) break; (void) fputs(text,stdout); text=DestroyString(text); break; } if (LocaleCompare(\"implode\",option+1) == 0) { \/* Implode image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=ImplodeImage(*image,geometry_info.rho,exception); break; } if (LocaleCompare(\"interline-spacing\",option+1) == 0) { if (*option == '+') (void) ParseGeometry(\"0\",&geometry_info); else (void) ParseGeometry(argv[i+1],&geometry_info); draw_info->interline_spacing=geometry_info.rho; break; } if (LocaleCompare(\"interword-spacing\",option+1) == 0) { if (*option == '+') (void) ParseGeometry(\"0\",&geometry_info); else (void) ParseGeometry(argv[i+1],&geometry_info); draw_info->interword_spacing=geometry_info.rho; break; } if (LocaleCompare(\"interpolative-resize\",option+1) == 0) { \/* Resize image using 'point sampled' interpolation *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=InterpolativeResizeImage(*image,geometry.width, geometry.height,(*image)->interpolate,exception); break; } break; } case 'k': { if (LocaleCompare(\"kerning\",option+1) == 0) { if (*option == '+') (void) ParseGeometry(\"0\",&geometry_info); else (void) ParseGeometry(argv[i+1],&geometry_info); draw_info->kerning=geometry_info.rho; break; } if (LocaleCompare(\"kuwahara\",option+1) == 0) { \/* Edge preserving blur. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho-0.5; mogrify_image=KuwaharaImageChannel(*image,channel,geometry_info.rho, geometry_info.sigma,exception); break; } break; } case 'l': { if (LocaleCompare(\"lat\",option+1) == 0) { \/* Local adaptive threshold image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & PercentValue) != 0) geometry_info.xi=(double) QuantumRange*geometry_info.xi\/100.0; mogrify_image=AdaptiveThresholdImage(*image,(size_t) geometry_info.rho,(size_t) geometry_info.sigma,(ssize_t) geometry_info.xi,exception); break; } if (LocaleCompare(\"level\",option+1) == 0) { MagickRealType black_point, gamma, white_point; MagickStatusType flags; \/* Parse levels. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); black_point=geometry_info.rho; white_point=(MagickRealType) QuantumRange; if ((flags & SigmaValue) != 0) white_point=geometry_info.sigma; gamma=1.0; if ((flags & XiValue) != 0) gamma=geometry_info.xi; if ((flags & PercentValue) != 0) { black_point*=(MagickRealType) (QuantumRange\/100.0); white_point*=(MagickRealType) (QuantumRange\/100.0); } if ((flags & SigmaValue) == 0) white_point=(MagickRealType) QuantumRange-black_point; if ((*option == '+') || ((flags & AspectValue) != 0)) (void) LevelizeImageChannel(*image,channel,black_point, white_point,gamma); else (void) LevelImageChannel(*image,channel,black_point,white_point, gamma); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"level-colors\",option+1) == 0) { char token[MaxTextExtent]; const char *p; MagickPixelPacket black_point, white_point; p=(const char *) argv[i+1]; GetNextToken(p,&p,MaxTextExtent,token); \/* get black point color *\/ if ((isalpha((int) *token) != 0) || ((*token == '#') != 0)) (void) QueryMagickColor(token,&black_point,exception); else (void) QueryMagickColor(\"#000000\",&black_point,exception); if (isalpha((int) token[0]) || (token[0] == '#')) GetNextToken(p,&p,MaxTextExtent,token); if (*token == '\\0') white_point=black_point; \/* set everything to that color *\/ else { if ((isalpha((int) *token) == 0) && ((*token == '#') == 0)) GetNextToken(p,&p,MaxTextExtent,token); \/* Get white point color. *\/ if ((isalpha((int) *token) != 0) || ((*token == '#') != 0)) (void) QueryMagickColor(token,&white_point,exception); else (void) QueryMagickColor(\"#ffffff\",&white_point,exception); } (void) LevelColorsImageChannel(*image,channel,&black_point, &white_point,*option == '+' ? MagickTrue : MagickFalse); break; } if (LocaleCompare(\"linear-stretch\",option+1) == 0) { double black_point, white_point; MagickStatusType flags; (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); black_point=geometry_info.rho; white_point=(MagickRealType) (*image)->columns*(*image)->rows; if ((flags & SigmaValue) != 0) white_point=geometry_info.sigma; if ((flags & PercentValue) != 0) { black_point*=(double) (*image)->columns*(*image)->rows\/100.0; white_point*=(double) (*image)->columns*(*image)->rows\/100.0; } if ((flags & SigmaValue) == 0) white_point=(MagickRealType) (*image)->columns*(*image)->rows- black_point; (void) LinearStretchImage(*image,black_point,white_point); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"linewidth\",option+1) == 0) { draw_info->stroke_width=StringToDouble(argv[i+1],(char **) NULL); break; } if (LocaleCompare(\"liquid-rescale\",option+1) == 0) { \/* Liquid rescale image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseRegionGeometry(*image,argv[i+1],&geometry,exception); if ((flags & XValue) == 0) geometry.x=1; if ((flags & YValue) == 0) geometry.y=0; mogrify_image=LiquidRescaleImage(*image,geometry.width, geometry.height,1.0*geometry.x,1.0*geometry.y,exception); break; } if (LocaleCompare(\"local-contrast\",option+1) == 0) { MagickStatusType flags; (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & RhoValue) == 0) geometry_info.rho=10; if ((flags & SigmaValue) == 0) geometry_info.sigma=12.5; mogrify_image=LocalContrastImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"lowlight-color\",option+1) == 0) { (void) SetImageArtifact(*image,\"compare:lowlight-color\",argv[i+1]); break; } break; } case 'm': { if (LocaleCompare(\"magnify\",option+1) == 0) { \/* Double image size. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=MagnifyImage(*image,exception); break; } if (LocaleCompare(\"map\",option+1) == 0) { Image *remap_image; \/* Transform image colors to match this set of colors. *\/ (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') break; remap_image=GetImageCache(mogrify_info,argv[i+1],exception); if (remap_image == (Image *) NULL) break; (void) RemapImage(quantize_info,*image,remap_image); InheritException(exception,&(*image)->exception); remap_image=DestroyImage(remap_image); break; } if (LocaleCompare(\"mask\",option+1) == 0) { Image *mask; (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') { \/* Remove a mask. *\/ (void) SetImageMask(*image,(Image *) NULL); InheritException(exception,&(*image)->exception); break; } \/* Set the image mask. *\/ mask=GetImageCache(mogrify_info,argv[i+1],exception); if (mask == (Image *) NULL) break; (void) SetImageMask(*image,mask); mask=DestroyImage(mask); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"matte\",option+1) == 0) { (void) SetImageAlphaChannel(*image,(*option == '-') ? SetAlphaChannel : DeactivateAlphaChannel ); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"mean-shift\",option+1) == 0) { \/* Delineate arbitrarily shaped clusters in the image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if ((flags & XiValue) == 0) geometry_info.xi=0.10*QuantumRange; if ((flags & PercentValue) != 0) geometry_info.xi=(double) QuantumRange*geometry_info.xi\/100.0; mogrify_image=MeanShiftImage(*image,(size_t) geometry_info.rho, (size_t) geometry_info.sigma,(size_t) geometry_info.xi,exception); break; } if (LocaleCompare(\"median\",option+1) == 0) { \/* Median filter image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=StatisticImageChannel(*image,channel,MedianStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.rho,exception); break; } if (LocaleCompare(\"mode\",option+1) == 0) { \/* Mode image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=StatisticImageChannel(*image,channel,ModeStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.rho,exception); break; } if (LocaleCompare(\"modulate\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); (void) ModulateImage(*image,argv[i+1]); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"moments\",option+1) == 0) { if (*option == '+') { (void) DeleteImageArtifact(*image,\"identify:moments\"); break; } (void) SetImageArtifact(*image,\"identify:moments\",argv[i+1]); (void) SetImageArtifact(*image,\"verbose\",\"true\"); break; } if (LocaleCompare(\"monitor\",option+1) == 0) { if (*option == '+') { (void) SetImageProgressMonitor(*image, (MagickProgressMonitor) NULL,(void *) NULL); break; } (void) SetImageProgressMonitor(*image,MonitorProgress, (void *) NULL); break; } if (LocaleCompare(\"monochrome\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); (void) SetImageType(*image,BilevelType); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"morphology\",option+1) == 0) { char token[MaxTextExtent]; const char *p; KernelInfo *kernel; MorphologyMethod method; ssize_t iterations; \/* Morphological Image Operation *\/ (void) SyncImageSettings(mogrify_info,*image); p=argv[i+1]; GetNextToken(p,&p,MaxTextExtent,token); method=(MorphologyMethod) ParseCommandOption( MagickMorphologyOptions,MagickFalse,token); iterations=1L; GetNextToken(p,&p,MaxTextExtent,token); if ((*p == ':') || (*p == ',')) GetNextToken(p,&p,MaxTextExtent,token); if ((*p != '\\0')) iterations=(ssize_t) StringToLong(p); kernel=AcquireKernelInfo(argv[i+2]); if (kernel == (KernelInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"UnabletoParseKernel\",\"morphology\"); status=MagickFalse; break; } mogrify_image=MorphologyImageChannel(*image,channel,method, iterations,kernel,exception); kernel=DestroyKernelInfo(kernel); break; } if (LocaleCompare(\"motion-blur\",option+1) == 0) { \/* Motion blur image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=MotionBlurImageChannel(*image,channel, geometry_info.rho,geometry_info.sigma,geometry_info.xi,exception); break; } break; } case 'n': { if (LocaleCompare(\"negate\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); (void) NegateImageChannel(*image,channel,*option == '+' ? MagickTrue : MagickFalse); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"noise\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); if (*option == '-') { flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; mogrify_image=StatisticImageChannel(*image,channel, NonpeakStatistic,(size_t) geometry_info.rho,(size_t) geometry_info.sigma,exception); } else { NoiseType noise; noise=(NoiseType) ParseCommandOption(MagickNoiseOptions, MagickFalse,argv[i+1]); mogrify_image=AddNoiseImageChannel(*image,channel,noise, exception); } break; } if (LocaleCompare(\"normalize\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); (void) NormalizeImageChannel(*image,channel); InheritException(exception,&(*image)->exception); break; } break; } case 'o': { if (LocaleCompare(\"opaque\",option+1) == 0) { MagickPixelPacket target; (void) SyncImageSettings(mogrify_info,*image); (void) QueryMagickColor(argv[i+1],&target,exception); (void) OpaquePaintImageChannel(*image,channel,&target,&fill, *option == '-' ? MagickFalse : MagickTrue); break; } if (LocaleCompare(\"ordered-dither\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); (void) OrderedPosterizeImageChannel(*image,channel,argv[i+1], exception); break; } break; } case 'p': { if (LocaleCompare(\"paint\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=OilPaintImage(*image,geometry_info.rho,exception); break; } if (LocaleCompare(\"pen\",option+1) == 0) { if (*option == '+') { (void) QueryColorDatabase(\"none\",&draw_info->fill,exception); break; } (void) QueryColorDatabase(argv[i+1],&draw_info->fill,exception); break; } if (LocaleCompare(\"perceptible\",option+1) == 0) { \/* Perceptible image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) PerceptibleImageChannel(*image,channel,StringToDouble( argv[i+1],(char **) NULL)); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"pointsize\",option+1) == 0) { if (*option == '+') (void) ParseGeometry(\"12\",&geometry_info); else (void) ParseGeometry(argv[i+1],&geometry_info); draw_info->pointsize=geometry_info.rho; break; } if (LocaleCompare(\"polaroid\",option+1) == 0) { double angle; RandomInfo *random_info; \/* Simulate a Polaroid picture. *\/ (void) SyncImageSettings(mogrify_info,*image); random_info=AcquireRandomInfo(); angle=22.5*(GetPseudoRandomValue(random_info)-0.5); random_info=DestroyRandomInfo(random_info); if (*option == '-') { SetGeometryInfo(&geometry_info); flags=ParseGeometry(argv[i+1],&geometry_info); angle=geometry_info.rho; } mogrify_image=PolaroidImage(*image,draw_info,angle,exception); break; } if (LocaleCompare(\"posterize\",option+1) == 0) { \/* Posterize image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) PosterizeImage(*image,StringToUnsignedLong(argv[i+1]), quantize_info->dither); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"preview\",option+1) == 0) { PreviewType preview_type; \/* Preview image. *\/ (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') preview_type=UndefinedPreview; else preview_type=(PreviewType) ParseCommandOption( MagickPreviewOptions,MagickFalse,argv[i+1]); mogrify_image=PreviewImage(*image,preview_type,exception); break; } if (LocaleCompare(\"profile\",option+1) == 0) { const char *name; const StringInfo *profile; Image *profile_image; ImageInfo *profile_info; (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') { \/* Remove a profile from the image. *\/ (void) ProfileImage(*image,argv[i+1],(const unsigned char *) NULL,0,MagickTrue); InheritException(exception,&(*image)->exception); break; } \/* Associate a profile with the image. *\/ profile_info=CloneImageInfo(mogrify_info); profile=GetImageProfile(*image,\"iptc\"); if (profile != (StringInfo *) NULL) profile_info->profile=(void *) CloneStringInfo(profile); profile_image=GetImageCache(profile_info,argv[i+1],exception); profile_info=DestroyImageInfo(profile_info); if (profile_image == (Image *) NULL) { StringInfo *profile; profile_info=CloneImageInfo(mogrify_info); (void) CopyMagickString(profile_info->filename,argv[i+1], MaxTextExtent); profile=FileToStringInfo(profile_info->filename,~0UL,exception); if (profile != (StringInfo *) NULL) { (void) SetImageInfo(profile_info,0,exception); (void) ProfileImage(*image,profile_info->magick, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),MagickFalse); profile=DestroyStringInfo(profile); } profile_info=DestroyImageInfo(profile_info); break; } ResetImageProfileIterator(profile_image); name=GetNextImageProfile(profile_image); while (name != (const char *) NULL) { profile=GetImageProfile(profile_image,name); if (profile != (StringInfo *) NULL) (void) ProfileImage(*image,name,GetStringInfoDatum(profile), (size_t) GetStringInfoLength(profile),MagickFalse); name=GetNextImageProfile(profile_image); } profile_image=DestroyImage(profile_image); break; } break; } case 'q': { if (LocaleCompare(\"quantize\",option+1) == 0) { if (*option == '+') { quantize_info->colorspace=UndefinedColorspace; break; } quantize_info->colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); break; } break; } case 'r': { if (LocaleCompare(\"radial-blur\",option+1) == 0 || LocaleCompare(\"rotational-blur\",option+1) == 0) { \/* Radial blur image. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=RotationalBlurImageChannel(*image,channel, StringToDouble(argv[i+1],(char **) NULL),exception); break; } if (LocaleCompare(\"raise\",option+1) == 0) { \/* Surround image with a raise of solid color. *\/ flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); (void) RaiseImage(*image,&geometry,*option == '-' ? MagickTrue : MagickFalse); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"random-threshold\",option+1) == 0) { \/* Threshold image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) RandomThresholdImageChannel(*image,channel,argv[i+1], exception); break; } if (LocaleCompare(\"recolor\",option+1) == 0) { KernelInfo *kernel; (void) SyncImageSettings(mogrify_info,*image); kernel=AcquireKernelInfo(argv[i+1]); if (kernel == (KernelInfo *) NULL) break; mogrify_image=ColorMatrixImage(*image,kernel,exception); kernel=DestroyKernelInfo(kernel); break; } if (LocaleCompare(\"region\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); if (region_image != (Image *) NULL) { \/* Composite region. *\/ (void) CompositeImage(region_image,region_image->matte != MagickFalse ? CopyCompositeOp : OverCompositeOp,*image, region_geometry.x,region_geometry.y); InheritException(exception,®ion_image->exception); *image=DestroyImage(*image); *image=region_image; region_image=(Image *) NULL; } if (*option == '+') break; \/* Apply transformations to a selected region of the image. *\/ (void) ParseGravityGeometry(*image,argv[i+1],®ion_geometry, exception); mogrify_image=CropImage(*image,®ion_geometry,exception); if (mogrify_image == (Image *) NULL) break; region_image=(*image); *image=mogrify_image; mogrify_image=(Image *) NULL; break; } if (LocaleCompare(\"render\",option+1) == 0) { (void) SyncImageSettings(mogrify_info,*image); draw_info->render=(*option == '+') ? MagickTrue : MagickFalse; break; } if (LocaleCompare(\"remap\",option+1) == 0) { Image *remap_image; \/* Transform image colors to match this set of colors. *\/ (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') break; remap_image=GetImageCache(mogrify_info,argv[i+1],exception); if (remap_image == (Image *) NULL) break; (void) RemapImage(quantize_info,*image,remap_image); InheritException(exception,&(*image)->exception); remap_image=DestroyImage(remap_image); break; } if (LocaleCompare(\"repage\",option+1) == 0) { if (*option == '+') { (void) ParseAbsoluteGeometry(\"0x0+0+0\",&(*image)->page); break; } (void) ResetImagePage(*image,argv[i+1]); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"resample\",option+1) == 0) { \/* Resample image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; mogrify_image=ResampleImage(*image,geometry_info.rho, geometry_info.sigma,(*image)->filter,(*image)->blur,exception); break; } if (LocaleCompare(\"resize\",option+1) == 0) { \/* Resize image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ResizeImage(*image,geometry.width,geometry.height, (*image)->filter,(*image)->blur,exception); break; } if (LocaleCompare(\"roll\",option+1) == 0) { \/* Roll image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); if ((flags & PercentValue) != 0) { geometry.x*=(double) (*image)->columns\/100.0; geometry.y*=(double) (*image)->rows\/100.0; } mogrify_image=RollImage(*image,geometry.x,geometry.y,exception); break; } if (LocaleCompare(\"rotate\",option+1) == 0) { char *geometry; \/* Check for conditional image rotation. *\/ (void) SyncImageSettings(mogrify_info,*image); if (strchr(argv[i+1],'>') != (char *) NULL) if ((*image)->columns <= (*image)->rows) break; if (strchr(argv[i+1],'<') != (char *) NULL) if ((*image)->columns >= (*image)->rows) break; \/* Rotate image. *\/ geometry=ConstantString(argv[i+1]); (void) SubstituteString(&geometry,\">\",\"\"); (void) SubstituteString(&geometry,\"<\",\"\"); (void) ParseGeometry(geometry,&geometry_info); geometry=DestroyString(geometry); mogrify_image=RotateImage(*image,geometry_info.rho,exception); break; } break; } case 's': { if (LocaleCompare(\"sample\",option+1) == 0) { \/* Sample image with pixel replication. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=SampleImage(*image,geometry.width,geometry.height, exception); break; } if (LocaleCompare(\"scale\",option+1) == 0) { \/* Resize image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ScaleImage(*image,geometry.width,geometry.height, exception); break; } if (LocaleCompare(\"selective-blur\",option+1) == 0) { \/* Selectively blur pixels within a contrast threshold. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & PercentValue) != 0) geometry_info.xi=(double) QuantumRange*geometry_info.xi\/100.0; mogrify_image=SelectiveBlurImageChannel(*image,channel, geometry_info.rho,geometry_info.sigma,geometry_info.xi,exception); break; } if (LocaleCompare(\"separate\",option+1) == 0) { \/* Break channels into separate images. WARNING: This can generate multiple images! *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=SeparateImages(*image,channel,exception); break; } if (LocaleCompare(\"sepia-tone\",option+1) == 0) { double threshold; \/* Sepia-tone image. *\/ (void) SyncImageSettings(mogrify_info,*image); threshold=StringToDoubleInterval(argv[i+1],(double) QuantumRange+ 1.0); mogrify_image=SepiaToneImage(*image,threshold,exception); break; } if (LocaleCompare(\"segment\",option+1) == 0) { \/* Segment image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; (void) SegmentImage(*image,(*image)->colorspace, mogrify_info->verbose,geometry_info.rho,geometry_info.sigma); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"set\",option+1) == 0) { char *value; \/* Set image option. *\/ if (*option == '+') { if (LocaleNCompare(argv[i+1],\"registry:\",9) == 0) (void) DeleteImageRegistry(argv[i+1]+9); else if (LocaleNCompare(argv[i+1],\"option:\",7) == 0) { (void) DeleteImageOption(mogrify_info,argv[i+1]+7); (void) DeleteImageArtifact(*image,argv[i+1]+7); } else (void) DeleteImageProperty(*image,argv[i+1]); break; } value=InterpretImageProperties(mogrify_info,*image,argv[i+2]); InheritException(exception,&(*image)->exception); if (value == (char *) NULL) break; if (LocaleNCompare(argv[i+1],\"registry:\",9) == 0) (void) SetImageRegistry(StringRegistryType,argv[i+1]+9,value, exception); else if (LocaleNCompare(argv[i+1],\"option:\",7) == 0) { (void) SetImageOption(image_info,argv[i+1]+7,value); (void) SetImageOption(mogrify_info,argv[i+1]+7,value); (void) SetImageArtifact(*image,argv[i+1]+7,value); } else (void) SetImageProperty(*image,argv[i+1],value); value=DestroyString(value); break; } if (LocaleCompare(\"shade\",option+1) == 0) { \/* Shade image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=ShadeImage(*image,(*option == '-') ? MagickTrue : MagickFalse,geometry_info.rho,geometry_info.sigma,exception); break; } if (LocaleCompare(\"shadow\",option+1) == 0) { \/* Shadow image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=4.0; if ((flags & PsiValue) == 0) geometry_info.psi=4.0; mogrify_image=ShadowImage(*image,geometry_info.rho, geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5),(ssize_t) ceil(geometry_info.psi-0.5),exception); break; } if (LocaleCompare(\"sharpen\",option+1) == 0) { \/* Sharpen image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=SharpenImageChannel(*image,channel,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"shave\",option+1) == 0) { \/* Shave the image edges. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParsePageGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ShaveImage(*image,&geometry,exception); break; } if (LocaleCompare(\"shear\",option+1) == 0) { \/* Shear image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; mogrify_image=ShearImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"sigmoidal-contrast\",option+1) == 0) { \/* Sigmoidal non-linearity contrast control. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=(double) QuantumRange\/2.0; if ((flags & PercentValue) != 0) geometry_info.sigma=(double) QuantumRange*geometry_info.sigma\/ 100.0; (void) SigmoidalContrastImageChannel(*image,channel, (*option == '-') ? MagickTrue : MagickFalse,geometry_info.rho, geometry_info.sigma); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"sketch\",option+1) == 0) { \/* Sketch image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=SketchImage(*image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,exception); break; } if (LocaleCompare(\"solarize\",option+1) == 0) { double threshold; (void) SyncImageSettings(mogrify_info,*image); threshold=StringToDoubleInterval(argv[i+1],(double) QuantumRange+ 1.0); (void) SolarizeImageChannel(*image,channel,threshold,exception); break; } if (LocaleCompare(\"sparse-color\",option+1) == 0) { SparseColorMethod method; char *arguments; \/* Sparse Color Interpolated Gradient *\/ (void) SyncImageSettings(mogrify_info,*image); method=(SparseColorMethod) ParseCommandOption( MagickSparseColorOptions,MagickFalse,argv[i+1]); arguments=InterpretImageProperties(mogrify_info,*image,argv[i+2]); InheritException(exception,&(*image)->exception); if (arguments == (char *) NULL) break; mogrify_image=SparseColorOption(*image,channel,method,arguments, option[0] == '+' ? MagickTrue : MagickFalse,exception); arguments=DestroyString(arguments); break; } if (LocaleCompare(\"splice\",option+1) == 0) { \/* Splice a solid color into the image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseGravityGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=SpliceImage(*image,&geometry,exception); break; } if (LocaleCompare(\"spread\",option+1) == 0) { \/* Spread an image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=SpreadImage(*image,geometry_info.rho,exception); break; } if (LocaleCompare(\"statistic\",option+1) == 0) { StatisticType type; (void) SyncImageSettings(mogrify_info,*image); type=(StatisticType) ParseCommandOption(MagickStatisticOptions, MagickFalse,argv[i+1]); (void) ParseGeometry(argv[i+2],&geometry_info); mogrify_image=StatisticImageChannel(*image,channel,type,(size_t) geometry_info.rho,(size_t) geometry_info.sigma,exception); break; } if (LocaleCompare(\"stretch\",option+1) == 0) { if (*option == '+') { draw_info->stretch=UndefinedStretch; break; } draw_info->stretch=(StretchType) ParseCommandOption( MagickStretchOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"strip\",option+1) == 0) { \/* Strip image of profiles and comments. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) StripImage(*image); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"stroke\",option+1) == 0) { ExceptionInfo *sans; if (*option == '+') { (void) QueryColorDatabase(\"none\",&draw_info->stroke,exception); if (draw_info->stroke_pattern != (Image *) NULL) draw_info->stroke_pattern=DestroyImage( draw_info->stroke_pattern); break; } sans=AcquireExceptionInfo(); status=QueryColorDatabase(argv[i+1],&draw_info->stroke,sans); sans=DestroyExceptionInfo(sans); if (status == MagickFalse) draw_info->stroke_pattern=GetImageCache(mogrify_info,argv[i+1], exception); break; } if (LocaleCompare(\"strokewidth\",option+1) == 0) { draw_info->stroke_width=StringToDouble(argv[i+1],(char **) NULL); break; } if (LocaleCompare(\"style\",option+1) == 0) { if (*option == '+') { draw_info->style=UndefinedStyle; break; } draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"swirl\",option+1) == 0) { \/* Swirl image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseGeometry(argv[i+1],&geometry_info); mogrify_image=SwirlImage(*image,geometry_info.rho,exception); break; } break; } case 't': { if (LocaleCompare(\"threshold\",option+1) == 0) { double threshold; \/* Threshold image. *\/ (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') threshold=(double) QuantumRange\/2; else threshold=StringToDoubleInterval(argv[i+1],(double) QuantumRange+ 1.0); (void) BilevelImageChannel(*image,channel,threshold); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"thumbnail\",option+1) == 0) { \/* Thumbnail image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) ParseRegionGeometry(*image,argv[i+1],&geometry,exception); mogrify_image=ThumbnailImage(*image,geometry.width,geometry.height, exception); break; } if (LocaleCompare(\"tile\",option+1) == 0) { if (*option == '+') { if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); break; } draw_info->fill_pattern=GetImageCache(mogrify_info,argv[i+1], exception); break; } if (LocaleCompare(\"tint\",option+1) == 0) { \/* Tint the image. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=TintImage(*image,argv[i+1],draw_info->fill,exception); break; } if (LocaleCompare(\"transform\",option+1) == 0) { \/* Affine transform image. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=AffineTransformImage(*image,&draw_info->affine, exception); break; } if (LocaleCompare(\"transparent\",option+1) == 0) { MagickPixelPacket target; (void) SyncImageSettings(mogrify_info,*image); (void) QueryMagickColor(argv[i+1],&target,exception); (void) TransparentPaintImage(*image,&target,(Quantum) TransparentOpacity,*option == '-' ? MagickFalse : MagickTrue); InheritException(exception,&(*image)->exception); break; } if (LocaleCompare(\"transpose\",option+1) == 0) { \/* Transpose image scanlines. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=TransposeImage(*image,exception); break; } if (LocaleCompare(\"transverse\",option+1) == 0) { \/* Transverse image scanlines. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=TransverseImage(*image,exception); break; } if (LocaleCompare(\"treedepth\",option+1) == 0) { quantize_info->tree_depth=StringToUnsignedLong(argv[i+1]); break; } if (LocaleCompare(\"trim\",option+1) == 0) { \/* Trim image. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=TrimImage(*image,exception); break; } if (LocaleCompare(\"type\",option+1) == 0) { ImageType type; (void) SyncImageSettings(mogrify_info,*image); if (*option == '+') type=UndefinedType; else type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse, argv[i+1]); (*image)->type=UndefinedType; (void) SetImageType(*image,type); InheritException(exception,&(*image)->exception); break; } break; } case 'u': { if (LocaleCompare(\"undercolor\",option+1) == 0) { (void) QueryColorDatabase(argv[i+1],&draw_info->undercolor, exception); break; } if (LocaleCompare(\"unique\",option+1) == 0) { if (*option == '+') { (void) DeleteImageArtifact(*image,\"identify:unique-colors\"); break; } (void) SetImageArtifact(*image,\"identify:unique-colors\",\"true\"); (void) SetImageArtifact(*image,\"verbose\",\"true\"); break; } if (LocaleCompare(\"unique-colors\",option+1) == 0) { \/* Unique image colors. *\/ (void) SyncImageSettings(mogrify_info,*image); mogrify_image=UniqueImageColors(*image,exception); break; } if (LocaleCompare(\"unsharp\",option+1) == 0) { \/* Unsharp mask image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=1.0; if ((flags & PsiValue) == 0) geometry_info.psi=0.05; mogrify_image=UnsharpMaskImageChannel(*image,channel, geometry_info.rho,geometry_info.sigma,geometry_info.xi, geometry_info.psi,exception); break; } break; } case 'v': { if (LocaleCompare(\"verbose\",option+1) == 0) { (void) SetImageArtifact(*image,option+1, *option == '+' ? \"false\" : \"true\"); break; } if (LocaleCompare(\"vignette\",option+1) == 0) { \/* Vignette image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=0.1*(*image)->columns; if ((flags & PsiValue) == 0) geometry_info.psi=0.1*(*image)->rows; if ((flags & PercentValue) != 0) { geometry_info.xi*=(double) (*image)->columns\/100.0; geometry_info.psi*=(double) (*image)->rows\/100.0; } mogrify_image=VignetteImage(*image,geometry_info.rho, geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5),(ssize_t) ceil(geometry_info.psi-0.5),exception); break; } if (LocaleCompare(\"virtual-pixel\",option+1) == 0) { if (*option == '+') { (void) SetImageVirtualPixelMethod(*image, UndefinedVirtualPixelMethod); break; } (void) SetImageVirtualPixelMethod(*image,(VirtualPixelMethod) ParseCommandOption(MagickVirtualPixelOptions,MagickFalse, argv[i+1])); break; } break; } case 'w': { if (LocaleCompare(\"wave\",option+1) == 0) { \/* Wave image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; mogrify_image=WaveImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"wavelet-denoise\",option+1) == 0) { \/* Wavelet denoise image. *\/ (void) SyncImageSettings(mogrify_info,*image); flags=ParseGeometry(argv[i+1],&geometry_info); if ((flags & PercentValue) != 0) { geometry_info.rho=QuantumRange*geometry_info.rho\/100.0; geometry_info.sigma=QuantumRange*geometry_info.sigma\/100.0; } if ((flags & SigmaValue) == 0) geometry_info.sigma=0.0; mogrify_image=WaveletDenoiseImage(*image,geometry_info.rho, geometry_info.sigma,exception); break; } if (LocaleCompare(\"weight\",option+1) == 0) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse, argv[i+1]); if (weight == -1) weight=StringToUnsignedLong(argv[i+1]); draw_info->weight=(size_t) weight; break; } if (LocaleCompare(\"white-threshold\",option+1) == 0) { \/* White threshold image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) WhiteThresholdImageChannel(*image,channel,argv[i+1], exception); InheritException(exception,&(*image)->exception); break; } break; } default: break; } \/* Replace current image with any image that was generated. *\/ if (mogrify_image != (Image *) NULL) ReplaceImageInListReturnLast(image,mogrify_image); i+=count; } if (region_image != (Image *) NULL) { \/* Composite transformed region onto image. *\/ (void) SyncImageSettings(mogrify_info,*image); (void) CompositeImage(region_image,region_image->matte != MagickFalse ? CopyCompositeOp : OverCompositeOp,*image,region_geometry.x, region_geometry.y); InheritException(exception,®ion_image->exception); *image=DestroyImage(*image); *image=region_image; region_image = (Image *) NULL; } \/* Free resources. *\/ quantize_info=DestroyQuantizeInfo(quantize_info); draw_info=DestroyDrawInfo(draw_info); mogrify_info=DestroyImageInfo(mogrify_info); status=(MagickStatusType) (exception->severity < ErrorException ? 1 : 0); return(status == 0 ? MagickFalse : MagickTrue); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":323103,"input":"void sqlite3Pragma( Parse *pParse, Token *pId1, \/* First part of [schema.]id field *\/ Token *pId2, \/* Second part of [schema.]id field, or NULL *\/ Token *pValue, \/* Token for , or NULL *\/ int minusFlag \/* True if a '-' sign preceded *\/ ){ char *zLeft = 0; \/* Nul-terminated UTF-8 string *\/ char *zRight = 0; \/* Nul-terminated UTF-8 string , or NULL *\/ const char *zDb = 0; \/* The database name *\/ Token *pId; \/* Pointer to token *\/ char *aFcntl[4]; \/* Argument to SQLITE_FCNTL_PRAGMA *\/ int iDb; \/* Database index for *\/ int rc; \/* return value form SQLITE_FCNTL_PRAGMA *\/ sqlite3 *db = pParse->db; \/* The database connection *\/ Db *pDb; \/* The specific database being pragmaed *\/ Vdbe *v = sqlite3GetVdbe(pParse); \/* Prepared statement *\/ const PragmaName *pPragma; \/* The pragma *\/ if( v==0 ) return; sqlite3VdbeRunOnlyOnce(v); pParse->nMem = 2; \/* Interpret the [schema.] part of the pragma statement. iDb is the ** index of the database this pragma is being applied to in db.aDb[]. *\/ iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); if( iDb<0 ) return; pDb = &db->aDb[iDb]; \/* If the temp database has been explicitly named as part of the ** pragma, make sure it is open. *\/ if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ return; } zLeft = sqlite3NameFromToken(db, pId); if( !zLeft ) return; if( minusFlag ){ zRight = sqlite3MPrintf(db, \"-%T\", pValue); }else{ zRight = sqlite3NameFromToken(db, pValue); } assert( pId2 ); zDb = pId2->n>0 ? pDb->zDbSName : 0; if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ goto pragma_out; } \/* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS ** connection. If it returns SQLITE_OK, then assume that the VFS ** handled the pragma and generate a no-op prepared statement. ** ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed, ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file ** object corresponding to the database file to which the pragma ** statement refers. ** ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA ** file control is an array of pointers to strings (char**) in which the ** second element of the array is the name of the pragma and the third ** element is the argument to the pragma or NULL if the pragma has no ** argument. *\/ aFcntl[0] = 0; aFcntl[1] = zLeft; aFcntl[2] = zRight; aFcntl[3] = 0; db->busyHandler.nBusy = 0; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); if( rc==SQLITE_OK ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT); returnSingleText(v, aFcntl[0]); sqlite3_free(aFcntl[0]); goto pragma_out; } if( rc!=SQLITE_NOTFOUND ){ if( aFcntl[0] ){ sqlite3ErrorMsg(pParse, \"%s\", aFcntl[0]); sqlite3_free(aFcntl[0]); } pParse->nErr++; pParse->rc = rc; goto pragma_out; } \/* Locate the pragma in the lookup table *\/ pPragma = pragmaLocate(zLeft); if( pPragma==0 ) goto pragma_out; \/* Make sure the database schema is loaded if the pragma requires that *\/ if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){ if( sqlite3ReadSchema(pParse) ) goto pragma_out; } \/* Register the result column names for pragmas that return results *\/ if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0) ){ setPragmaResultColumnNames(v, pPragma); } \/* Jump to the appropriate pragma handler *\/ switch( pPragma->ePragTyp ){ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) \/* ** PRAGMA [schema.]default_cache_size ** PRAGMA [schema.]default_cache_size=N ** ** The first form reports the current persistent setting for the ** page cache size. The value returned is the maximum number of ** pages in the page cache. The second form sets both the current ** page cache size value and the persistent page cache size value ** stored in the database file. ** ** Older versions of SQLite would set the default cache size to a ** negative number to indicate synchronous=OFF. These days, synchronous ** is always on by default regardless of the sign of the default cache ** size. But continue to take the absolute value of the default cache ** size of historical compatibility. *\/ case PragTyp_DEFAULT_CACHE_SIZE: { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList getCacheSize[] = { { OP_Transaction, 0, 0, 0}, \/* 0 *\/ { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, \/* 1 *\/ { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 2, 0}, { OP_Subtract, 1, 2, 1}, { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 1, 0}, \/* 6 *\/ { OP_Noop, 0, 0, 0}, { OP_ResultRow, 1, 1, 0}, }; VdbeOp *aOp; sqlite3VdbeUsesBtree(v, iDb); if( !zRight ){ pParse->nMem += 2; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize)); aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE; }else{ int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } #endif \/* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED *\/ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) \/* ** PRAGMA [schema.]page_size ** PRAGMA [schema.]page_size=N ** ** The first form reports the current setting for the ** database page size in bytes. The second form sets the ** database page size value. The value can only be set if ** the database has not yet been created. *\/ case PragTyp_PAGE_SIZE: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; returnSingleInt(v, size); }else{ \/* Malloc may fail when setting the page-size, as there is an internal ** buffer that the pager module resizes using sqlite3_realloc(). *\/ db->nextPagesize = sqlite3Atoi(zRight); if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ sqlite3OomFault(db); } } break; } \/* ** PRAGMA [schema.]secure_delete ** PRAGMA [schema.]secure_delete=ON\/OFF\/FAST ** ** The first form reports the current setting for the ** secure_delete flag. The second form changes the secure_delete ** flag setting and reports the new value. *\/ case PragTyp_SECURE_DELETE: { Btree *pBt = pDb->pBt; int b = -1; assert( pBt!=0 ); if( zRight ){ if( sqlite3_stricmp(zRight, \"fast\")==0 ){ b = 2; }else{ b = sqlite3GetBoolean(zRight, 0); } } if( pId2->n==0 && b>=0 ){ int ii; for(ii=0; iinDb; ii++){ sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); } } b = sqlite3BtreeSecureDelete(pBt, b); returnSingleInt(v, b); break; } \/* ** PRAGMA [schema.]max_page_count ** PRAGMA [schema.]max_page_count=N ** ** The first form reports the current setting for the ** maximum number of pages in the database file. The ** second form attempts to change this setting. Both ** forms return the current setting. ** ** The absolute value of N is used. This is undocumented and might ** change. The only purpose is to provide an easy way to test ** the sqlite3AbsInt32() function. ** ** PRAGMA [schema.]page_count ** ** Return the number of pages in the specified database. *\/ case PragTyp_PAGE_COUNT: { int iReg; sqlite3CodeVerifySchema(pParse, iDb); iReg = ++pParse->nMem; if( sqlite3Tolower(zLeft[0])=='p' ){ sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); }else{ sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3AbsInt32(sqlite3Atoi(zRight))); } sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); break; } \/* ** PRAGMA [schema.]locking_mode ** PRAGMA [schema.]locking_mode = (normal|exclusive) *\/ case PragTyp_LOCKING_MODE: { const char *zRet = \"normal\"; int eMode = getLockingMode(zRight); if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){ \/* Simple \"PRAGMA locking_mode;\" statement. This is a query for ** the current default locking mode (which may be different to ** the locking-mode of the main database). *\/ eMode = db->dfltLockMode; }else{ Pager *pPager; if( pId2->n==0 ){ \/* This indicates that no database name was specified as part ** of the PRAGMA command. In this case the locking-mode must be ** set on all attached databases, as well as the main db file. ** ** Also, the sqlite3.dfltLockMode variable is set so that ** any subsequently attached databases also use the specified ** locking mode. *\/ int ii; assert(pDb==&db->aDb[0]); for(ii=2; iinDb; ii++){ pPager = sqlite3BtreePager(db->aDb[ii].pBt); sqlite3PagerLockingMode(pPager, eMode); } db->dfltLockMode = (u8)eMode; } pPager = sqlite3BtreePager(pDb->pBt); eMode = sqlite3PagerLockingMode(pPager, eMode); } assert( eMode==PAGER_LOCKINGMODE_NORMAL || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ zRet = \"exclusive\"; } returnSingleText(v, zRet); break; } \/* ** PRAGMA [schema.]journal_mode ** PRAGMA [schema.]journal_mode = ** (delete|persist|off|truncate|memory|wal|off) *\/ case PragTyp_JOURNAL_MODE: { int eMode; \/* One of the PAGER_JOURNALMODE_XXX symbols *\/ int ii; \/* Loop counter *\/ if( zRight==0 ){ \/* If there is no \"=MODE\" part of the pragma, do a query for the ** current mode *\/ eMode = PAGER_JOURNALMODE_QUERY; }else{ const char *zMode; int n = sqlite3Strlen30(zRight); for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; } if( !zMode ){ \/* If the \"=MODE\" part does not match any known journal mode, ** then do a query *\/ eMode = PAGER_JOURNALMODE_QUERY; } if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){ \/* Do not allow journal-mode \"OFF\" in defensive since the database ** can become corrupted using ordinary SQL when the journal is off *\/ eMode = PAGER_JOURNALMODE_QUERY; } } if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ \/* Convert \"PRAGMA journal_mode\" into \"PRAGMA main.journal_mode\" *\/ iDb = 0; pId2->n = 1; } for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3VdbeUsesBtree(v, ii); sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); } } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); break; } \/* ** PRAGMA [schema.]journal_size_limit ** PRAGMA [schema.]journal_size_limit=N ** ** Get or set the size limit on rollback journal files. *\/ case PragTyp_JOURNAL_SIZE_LIMIT: { Pager *pPager = sqlite3BtreePager(pDb->pBt); i64 iLimit = -2; if( zRight ){ sqlite3DecOrHexToI64(zRight, &iLimit); if( iLimit<-1 ) iLimit = -1; } iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); returnSingleInt(v, iLimit); break; } #endif \/* SQLITE_OMIT_PAGER_PRAGMAS *\/ \/* ** PRAGMA [schema.]auto_vacuum ** PRAGMA [schema.]auto_vacuum=N ** ** Get or set the value of the database 'auto-vacuum' parameter. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL *\/ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_AUTO_VACUUM: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt)); }else{ int eAuto = getAutoVacuum(zRight); assert( eAuto>=0 && eAuto<=2 ); db->nextAutovac = (u8)eAuto; \/* Call SetAutoVacuum() to set initialize the internal auto and ** incr-vacuum flags. This is required in case this connection ** creates the database file. It is important that it is created ** as an auto-vacuum capable db. *\/ rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ \/* When setting the auto_vacuum mode to either \"full\" or ** \"incremental\", write the value of meta[6] in the database ** file. Before writing to meta[6], check that meta[3] indicates ** that this really is an auto-vacuum capable database. *\/ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList setMeta6[] = { { OP_Transaction, 0, 1, 0}, \/* 0 *\/ { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE}, { OP_If, 1, 0, 0}, \/* 2 *\/ { OP_Halt, SQLITE_OK, OE_Abort, 0}, \/* 3 *\/ { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, \/* 4 *\/ }; VdbeOp *aOp; int iAddr = sqlite3VdbeCurrentAddr(v); sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[2].p2 = iAddr+4; aOp[4].p1 = iDb; aOp[4].p3 = eAuto - 1; sqlite3VdbeUsesBtree(v, iDb); } } break; } #endif \/* ** PRAGMA [schema.]incremental_vacuum(N) ** ** Do N steps of incremental vacuuming on a database. *\/ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_INCREMENTAL_VACUUM: { int iLimit, addr; if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ iLimit = 0x7fffffff; } sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v); sqlite3VdbeAddOp1(v, OP_ResultRow, 1); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr); break; } #endif #ifndef SQLITE_OMIT_PAGER_PRAGMAS \/* ** PRAGMA [schema.]cache_size ** PRAGMA [schema.]cache_size=N ** ** The first form reports the current local setting for the ** page cache size. The second form sets the local ** page cache size value. If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. *\/ case PragTyp_CACHE_SIZE: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, pDb->pSchema->cache_size); }else{ int size = sqlite3Atoi(zRight); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } \/* ** PRAGMA [schema.]cache_spill ** PRAGMA cache_spill=BOOLEAN ** PRAGMA [schema.]cache_spill=N ** ** The first form reports the current local setting for the ** page cache spill size. The second form turns cache spill on ** or off. When turnning cache spill on, the size is set to the ** current cache_size. The third form sets a spill size that ** may be different form the cache size. ** If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. ** ** If the number of cache_spill pages is less then the number of ** cache_size pages, no spilling occurs until the page count exceeds ** the number of cache_size pages. ** ** The cache_spill=BOOLEAN setting applies to all attached schemas, ** not just the schema specified. *\/ case PragTyp_CACHE_SPILL: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, (db->flags & SQLITE_CacheSpill)==0 ? 0 : sqlite3BtreeSetSpillSize(pDb->pBt,0)); }else{ int size = 1; if( sqlite3GetInt32(zRight, &size) ){ sqlite3BtreeSetSpillSize(pDb->pBt, size); } if( sqlite3GetBoolean(zRight, size!=0) ){ db->flags |= SQLITE_CacheSpill; }else{ db->flags &= ~(u64)SQLITE_CacheSpill; } setAllPagerFlags(db); } break; } \/* ** PRAGMA [schema.]mmap_size(N) ** ** Used to set mapping size limit. The mapping size limit is ** used to limit the aggregate size of all memory mapped regions of the ** database file. If this parameter is set to zero, then memory mapping ** is not used at all. If N is negative, then the default memory map ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. ** The parameter N is measured in bytes. ** ** This value is advisory. The underlying VFS is free to memory map ** as little or as much as it wants. Except, if N is set to 0 then the ** upper layers will never invoke the xFetch interfaces to the VFS. *\/ case PragTyp_MMAP_SIZE: { sqlite3_int64 sz; #if SQLITE_MAX_MMAP_SIZE>0 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( zRight ){ int ii; sqlite3DecOrHexToI64(zRight, &sz); if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; if( pId2->n==0 ) db->szMmap = sz; for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); } } } sz = -1; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); #else sz = 0; rc = SQLITE_OK; #endif if( rc==SQLITE_OK ){ returnSingleInt(v, sz); }else if( rc!=SQLITE_NOTFOUND ){ pParse->nErr++; pParse->rc = rc; } break; } \/* ** PRAGMA temp_store ** PRAGMA temp_store = \"default\"|\"memory\"|\"file\" ** ** Return or set the local value of the temp_store flag. Changing ** the local value does not make changes to the disk file and the default ** value will be restored the next time the database is opened. ** ** Note that it is possible for the library compile-time options to ** override this setting *\/ case PragTyp_TEMP_STORE: { if( !zRight ){ returnSingleInt(v, db->temp_store); }else{ changeTempStorage(pParse, zRight); } break; } \/* ** PRAGMA temp_store_directory ** PRAGMA temp_store_directory = \"\"|\"directory_name\" ** ** Return or set the local value of the temp_store_directory flag. Changing ** the value sets a specific directory to be used for temporary files. ** Setting to a null string reverts to the default temporary directory search. ** If temporary directory is changed, then invalidateTempStorage. ** *\/ case PragTyp_TEMP_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, sqlite3_temp_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, \"not a writable directory\"); goto pragma_out; } } if( SQLITE_TEMP_STORE==0 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) || (SQLITE_TEMP_STORE==2 && db->temp_store==1) ){ invalidateTempStorage(pParse); } sqlite3_free(sqlite3_temp_directory); if( zRight[0] ){ sqlite3_temp_directory = sqlite3_mprintf(\"%s\", zRight); }else{ sqlite3_temp_directory = 0; } #endif \/* SQLITE_OMIT_WSD *\/ } break; } #if SQLITE_OS_WIN \/* ** PRAGMA data_store_directory ** PRAGMA data_store_directory = \"\"|\"directory_name\" ** ** Return or set the local value of the data_store_directory flag. Changing ** the value sets a specific directory to be used for database files that ** were specified with a relative pathname. Setting to a null string reverts ** to the default database directory, which for database files specified with ** a relative path will probably be based on the current directory for the ** process. Database file specified with an absolute path are not impacted ** by this setting, regardless of its value. ** *\/ case PragTyp_DATA_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, sqlite3_data_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, \"not a writable directory\"); goto pragma_out; } } sqlite3_free(sqlite3_data_directory); if( zRight[0] ){ sqlite3_data_directory = sqlite3_mprintf(\"%s\", zRight); }else{ sqlite3_data_directory = 0; } #endif \/* SQLITE_OMIT_WSD *\/ } break; } #endif #if SQLITE_ENABLE_LOCKING_STYLE \/* ** PRAGMA [schema.]lock_proxy_file ** PRAGMA [schema.]lock_proxy_file = \":auto:\"|\"lock_file_path\" ** ** Return or set the value of the lock_proxy_file flag. Changing ** the value sets a specific file to be used for database access locks. ** *\/ case PragTyp_LOCK_PROXY_FILE: { if( !zRight ){ Pager *pPager = sqlite3BtreePager(pDb->pBt); char *proxy_file_path = NULL; sqlite3_file *pFile = sqlite3PagerFile(pPager); sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, &proxy_file_path); returnSingleText(v, proxy_file_path); }else{ Pager *pPager = sqlite3BtreePager(pDb->pBt); sqlite3_file *pFile = sqlite3PagerFile(pPager); int res; if( zRight[0] ){ res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, zRight); } else { res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, NULL); } if( res!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, \"failed to set lock proxy file\"); goto pragma_out; } } break; } #endif \/* SQLITE_ENABLE_LOCKING_STYLE *\/ \/* ** PRAGMA [schema.]synchronous ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA ** ** Return or set the local value of the synchronous flag. Changing ** the local value does not make changes to the disk file and the ** default value will be restored the next time the database is ** opened. *\/ case PragTyp_SYNCHRONOUS: { if( !zRight ){ returnSingleInt(v, pDb->safety_level-1); }else{ if( !db->autoCommit ){ sqlite3ErrorMsg(pParse, \"Safety level may not be changed inside a transaction\"); }else if( iDb!=1 ){ int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK; if( iLevel==0 ) iLevel = 1; pDb->safety_level = iLevel; pDb->bSyncSet = 1; setAllPagerFlags(db); } } break; } #endif \/* SQLITE_OMIT_PAGER_PRAGMAS *\/ #ifndef SQLITE_OMIT_FLAG_PRAGMAS case PragTyp_FLAG: { if( zRight==0 ){ setPragmaResultColumnNames(v, pPragma); returnSingleInt(v, (db->flags & pPragma->iArg)!=0 ); }else{ u64 mask = pPragma->iArg; \/* Mask of bits to set or clear. *\/ if( db->autoCommit==0 ){ \/* Foreign key support may not be enabled or disabled while not ** in auto-commit mode. *\/ mask &= ~(SQLITE_ForeignKeys); } #if SQLITE_USER_AUTHENTICATION if( db->auth.authLevel==UAUTH_User ){ \/* Do not allow non-admin users to modify the schema arbitrarily *\/ mask &= ~(SQLITE_WriteSchema); } #endif if( sqlite3GetBoolean(zRight, 0) ){ db->flags |= mask; }else{ db->flags &= ~mask; if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; } \/* Many of the flag-pragmas modify the code generated by the SQL ** compiler (eg. count_changes). So add an opcode to expire all ** compiled SQL statements after modifying a pragma value. *\/ sqlite3VdbeAddOp0(v, OP_Expire); setAllPagerFlags(db); } break; } #endif \/* SQLITE_OMIT_FLAG_PRAGMAS *\/ #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS \/* ** PRAGMA table_info(
) ** ** Return a single row for each column of the named table. The columns of ** the returned data set are: ** ** cid: Column id (numbered from left to right, starting at 0) ** name: Column name ** type: Column declaration type. ** notnull: True if 'NOT NULL' is part of column declaration ** dflt_value: The default value for the column, if any. ** pk: Non-zero for PK fields. *\/ case PragTyp_TABLE_INFO: if( zRight ){ Table *pTab; pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); if( pTab ){ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); int i, k; int nHidden = 0; Column *pCol; Index *pPk = sqlite3PrimaryKeyIndex(pTab); pParse->nMem = 7; sqlite3CodeVerifySchema(pParse, iTabDb); sqlite3ViewGetColumnNames(pParse, pTab); for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ int isHidden = 0; if( pCol->colFlags & COLFLAG_NOINSERT ){ if( pPragma->iArg==0 ){ nHidden++; continue; } if( pCol->colFlags & COLFLAG_VIRTUAL ){ isHidden = 2; \/* GENERATED ALWAYS AS ... VIRTUAL *\/ }else if( pCol->colFlags & COLFLAG_STORED ){ isHidden = 3; \/* GENERATED ALWAYS AS ... STORED *\/ }else{ assert( pCol->colFlags & COLFLAG_HIDDEN ); isHidden = 1; \/* HIDDEN *\/ } } if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ k = 0; }else if( pPk==0 ){ k = 1; }else{ for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){} } assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 ); sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? \"issisii\" : \"issisi\", i-nHidden, pCol->zName, sqlite3ColumnType(pCol,\"\"), pCol->notNull ? 1 : 0, pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0, k, isHidden); } } } break; #ifdef SQLITE_DEBUG case PragTyp_STATS: { Index *pIdx; HashElem *i; pParse->nMem = 5; sqlite3CodeVerifySchema(pParse, iDb); for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ Table *pTab = sqliteHashData(i); sqlite3VdbeMultiLoad(v, 1, \"ssiii\", pTab->zName, 0, pTab->szTabRow, pTab->nRowLogEst, pTab->tabFlags); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ sqlite3VdbeMultiLoad(v, 2, \"siiiX\", pIdx->zName, pIdx->szIdxRow, pIdx->aiRowLogEst[0], pIdx->hasStat1); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); } } } break; #endif case PragTyp_INDEX_INFO: if( zRight ){ Index *pIdx; Table *pTab; pIdx = sqlite3FindIndex(db, zRight, zDb); if( pIdx==0 ){ \/* If there is no index named zRight, check to see if there is a ** WITHOUT ROWID table named zRight, and if there is, show the ** structure of the PRIMARY KEY index for that table. *\/ pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); if( pTab && !HasRowid(pTab) ){ pIdx = sqlite3PrimaryKeyIndex(pTab); } } if( pIdx ){ int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema); int i; int mx; if( pPragma->iArg ){ \/* PRAGMA index_xinfo (newer version with more rows and columns) *\/ mx = pIdx->nColumn; pParse->nMem = 6; }else{ \/* PRAGMA index_info (legacy version) *\/ mx = pIdx->nKeyCol; pParse->nMem = 3; } pTab = pIdx->pTable; sqlite3CodeVerifySchema(pParse, iIdxDb); assert( pParse->nMem<=pPragma->nPragCName ); for(i=0; iaiColumn[i]; sqlite3VdbeMultiLoad(v, 1, \"iisX\", i, cnum, cnum<0 ? 0 : pTab->aCol[cnum].zName); if( pPragma->iArg ){ sqlite3VdbeMultiLoad(v, 4, \"isiX\", pIdx->aSortOrder[i], pIdx->azColl[i], inKeyCol); } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem); } } } break; case PragTyp_INDEX_LIST: if( zRight ){ Index *pIdx; Table *pTab; int i; pTab = sqlite3FindTable(db, zRight, zDb); if( pTab ){ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); pParse->nMem = 5; sqlite3CodeVerifySchema(pParse, iTabDb); for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ const char *azOrigin[] = { \"c\", \"u\", \"pk\" }; sqlite3VdbeMultiLoad(v, 1, \"isisi\", i, pIdx->zName, IsUniqueIndex(pIdx), azOrigin[pIdx->idxType], pIdx->pPartIdxWhere!=0); } } } break; case PragTyp_DATABASE_LIST: { int i; pParse->nMem = 3; for(i=0; inDb; i++){ if( db->aDb[i].pBt==0 ) continue; assert( db->aDb[i].zDbSName!=0 ); sqlite3VdbeMultiLoad(v, 1, \"iss\", i, db->aDb[i].zDbSName, sqlite3BtreeGetFilename(db->aDb[i].pBt)); } } break; case PragTyp_COLLATION_LIST: { int i = 0; HashElem *p; pParse->nMem = 2; for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ CollSeq *pColl = (CollSeq *)sqliteHashData(p); sqlite3VdbeMultiLoad(v, 1, \"is\", i++, pColl->zName); } } break; #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS case PragTyp_FUNCTION_LIST: { int i; HashElem *j; FuncDef *p; pParse->nMem = 2; for(i=0; iu.pHash ){ if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue; sqlite3VdbeMultiLoad(v, 1, \"si\", p->zName, 1); } } for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){ p = (FuncDef*)sqliteHashData(j); sqlite3VdbeMultiLoad(v, 1, \"si\", p->zName, 0); } } break; #ifndef SQLITE_OMIT_VIRTUALTABLE case PragTyp_MODULE_LIST: { HashElem *j; pParse->nMem = 1; for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){ Module *pMod = (Module*)sqliteHashData(j); sqlite3VdbeMultiLoad(v, 1, \"s\", pMod->zName); } } break; #endif \/* SQLITE_OMIT_VIRTUALTABLE *\/ case PragTyp_PRAGMA_LIST: { int i; for(i=0; ipFKey; if( pFK ){ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); int i = 0; pParse->nMem = 8; sqlite3CodeVerifySchema(pParse, iTabDb); while(pFK){ int j; for(j=0; jnCol; j++){ sqlite3VdbeMultiLoad(v, 1, \"iissssss\", i, j, pFK->zTo, pTab->aCol[pFK->aCol[j].iFrom].zName, pFK->aCol[j].zCol, actionName(pFK->aAction[1]), \/* ON UPDATE *\/ actionName(pFK->aAction[0]), \/* ON DELETE *\/ \"NONE\"); } ++i; pFK = pFK->pNextFrom; } } } } break; #endif \/* !defined(SQLITE_OMIT_FOREIGN_KEY) *\/ #ifndef SQLITE_OMIT_FOREIGN_KEY #ifndef SQLITE_OMIT_TRIGGER case PragTyp_FOREIGN_KEY_CHECK: { FKey *pFK; \/* A foreign key constraint *\/ Table *pTab; \/* Child table contain \"REFERENCES\" keyword *\/ Table *pParent; \/* Parent table that child points to *\/ Index *pIdx; \/* Index in the parent table *\/ int i; \/* Loop counter: Foreign key number for pTab *\/ int j; \/* Loop counter: Field of the foreign key *\/ HashElem *k; \/* Loop counter: Next table in schema *\/ int x; \/* result variable *\/ int regResult; \/* 3 registers to hold a result row *\/ int regKey; \/* Register to hold key for checking the FK *\/ int regRow; \/* Registers to hold a row from pTab *\/ int addrTop; \/* Top of a loop checking foreign keys *\/ int addrOk; \/* Jump here if the key is OK *\/ int *aiCols; \/* child to parent column mapping *\/ regResult = pParse->nMem+1; pParse->nMem += 4; regKey = ++pParse->nMem; regRow = ++pParse->nMem; k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); while( k ){ int iTabDb; if( zRight ){ pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); k = 0; }else{ pTab = (Table*)sqliteHashData(k); k = sqliteHashNext(k); } if( pTab==0 || pTab->pFKey==0 ) continue; iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3CodeVerifySchema(pParse, iTabDb); sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName); if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead); sqlite3VdbeLoadString(v, regResult, pTab->zName); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); if( pParent==0 ) continue; pIdx = 0; sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName); x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); if( x==0 ){ if( pIdx==0 ){ sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead); }else{ sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); } }else{ k = 0; break; } } assert( pParse->nErr>0 || pFK==0 ); if( pFK ) break; if( pParse->nTabnTab = i; addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); pIdx = 0; aiCols = 0; if( pParent ){ x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); assert( x==0 ); } addrOk = sqlite3VdbeMakeLabel(pParse); \/* Generate code to read the child key values into registers ** regRow..regRow+n. If any of the child key values are NULL, this ** row cannot cause an FK violation. Jump directly to addrOk in ** this case. *\/ for(j=0; jnCol; j++){ int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom; sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j); sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v); } \/* Generate code to query the parent index for a matching parent ** key. If a match is found, jump to addrOk. *\/ if( pIdx ){ sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey, sqlite3IndexAffinityStr(db,pIdx), pFK->nCol); sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); VdbeCoverage(v); }else if( pParent ){ int jmp = sqlite3VdbeCurrentAddr(v)+2; sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v); sqlite3VdbeGoto(v, addrOk); assert( pFK->nCol==1 ); } \/* Generate code to report an FK violation to the caller. *\/ if( HasRowid(pTab) ){ sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1); } sqlite3VdbeMultiLoad(v, regResult+2, \"siX\", pFK->zTo, i-1); sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); sqlite3VdbeResolveLabel(v, addrOk); sqlite3DbFree(db, aiCols); } sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrTop); } } break; #endif \/* !defined(SQLITE_OMIT_TRIGGER) *\/ #endif \/* !defined(SQLITE_OMIT_FOREIGN_KEY) *\/ #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA \/* Reinstall the LIKE and GLOB functions. The variant of LIKE ** used will be case sensitive or not depending on the RHS. *\/ case PragTyp_CASE_SENSITIVE_LIKE: { if( zRight ){ sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); } } break; #endif \/* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA *\/ #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 #endif #ifndef SQLITE_OMIT_INTEGRITY_CHECK \/* PRAGMA integrity_check ** PRAGMA integrity_check(N) ** PRAGMA quick_check ** PRAGMA quick_check(N) ** ** Verify the integrity of the database. ** ** The \"quick_check\" is reduced version of ** integrity_check designed to detect most database corruption ** without the overhead of cross-checking indexes. Quick_check ** is linear time wherease integrity_check is O(NlogN). *\/ case PragTyp_INTEGRITY_CHECK: { int i, j, addr, mxErr; int isQuick = (sqlite3Tolower(zLeft[0])=='q'); \/* If the PRAGMA command was of the form \"PRAGMA .integrity_check\", ** then iDb is set to the index of the database identified by . ** In this case, the integrity of database iDb only is verified by ** the VDBE created below. ** ** Otherwise, if the command was simply \"PRAGMA integrity_check\" (or ** \"PRAGMA quick_check\"), then iDb is set to 0. In this case, set iDb ** to -1 here, to indicate that the VDBE should verify the integrity ** of all attached databases. *\/ assert( iDb>=0 ); assert( iDb==0 || pId2->z ); if( pId2->z==0 ) iDb = -1; \/* Initialize the VDBE program *\/ pParse->nMem = 6; \/* Set the maximum error count *\/ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; if( zRight ){ sqlite3GetInt32(zRight, &mxErr); if( mxErr<=0 ){ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; } } sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); \/* reg[1] holds errors left *\/ \/* Do an integrity check on each database file *\/ for(i=0; inDb; i++){ HashElem *x; \/* For looping over tables in the schema *\/ Hash *pTbls; \/* Set of all tables in the schema *\/ int *aRoot; \/* Array of root page numbers of all btrees *\/ int cnt = 0; \/* Number of entries in aRoot[] *\/ int mxIdx = 0; \/* Maximum number of indexes for any table *\/ if( OMIT_TEMPDB && i==1 ) continue; if( iDb>=0 && i!=iDb ) continue; sqlite3CodeVerifySchema(pParse, i); \/* Do an integrity check of the B-Tree ** ** Begin by finding the root pages numbers ** for all tables and indices in the database. *\/ assert( sqlite3SchemaMutexHeld(db, i, 0) ); pTbls = &db->aDb[i].pSchema->tblHash; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); \/* Current table *\/ Index *pIdx; \/* An index on pTab *\/ int nIdx; \/* Number of indexes on pTab *\/ if( HasRowid(pTab) ) cnt++; for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } if( nIdx>mxIdx ) mxIdx = nIdx; } aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); if( aRoot==0 ) break; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ aRoot[++cnt] = pIdx->tnum; } } aRoot[0] = cnt; \/* Make sure sufficient number of registers have been allocated *\/ pParse->nMem = MAX( pParse->nMem, 8+mxIdx ); sqlite3ClearTempRegCache(pParse); \/* Do the b-tree integrity checks *\/ sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY); sqlite3VdbeChangeP5(v, (u8)i); addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, sqlite3MPrintf(db, \"*** in database %s ***\\n\", db->aDb[i].zDbSName), P4_DYNAMIC); sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3); integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, addr); \/* Make sure all the indices are constructed correctly. *\/ for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx, *pPk; Index *pPrior = 0; int loopTop; int iDataCur, iIdxCur; int r1 = -1; if( pTab->tnum<1 ) continue; \/* Skip VIEWs or VIRTUAL TABLEs *\/ pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0, 1, 0, &iDataCur, &iIdxCur); \/* reg[7] counts the number of entries in the table. ** reg[8+i] counts the number of entries in the i-th index *\/ sqlite3VdbeAddOp2(v, OP_Integer, 0, 7); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); \/* index entries counter *\/ } assert( pParse->nMem>=8+j ); assert( sqlite3NoTempsInRange(pParse,1,7+j) ); sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v); loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); if( !isQuick ){ \/* Sanity check on record header decoding *\/ sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); } \/* Verify that all NOT NULL columns really are NOT NULL *\/ for(j=0; jnCol; j++){ char *zErr; int jmp2; if( j==pTab->iPKey ) continue; if( pTab->aCol[j].notNull==0 ) continue; sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3); if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){ sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); } jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v); zErr = sqlite3MPrintf(db, \"NULL value in %s.%s\", pTab->zName, pTab->aCol[j].zName); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, jmp2); } \/* Verify CHECK constraints *\/ if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0); if( db->mallocFailed==0 ){ int addrCkFault = sqlite3VdbeMakeLabel(pParse); int addrCkOk = sqlite3VdbeMakeLabel(pParse); char *zErr; int k; pParse->iSelfTab = iDataCur + 1; for(k=pCheck->nExpr-1; k>0; k--){ sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0); } sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, SQLITE_JUMPIFNULL); sqlite3VdbeResolveLabel(v, addrCkFault); pParse->iSelfTab = 0; zErr = sqlite3MPrintf(db, \"CHECK constraint failed in %s\", pTab->zName); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); integrityCheckResultRow(v); sqlite3VdbeResolveLabel(v, addrCkOk); } sqlite3ExprListDelete(db, pCheck); } if( !isQuick ){ \/* Omit the remaining tests for quick_check *\/ \/* Validate index entries for the current row *\/ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int jmp2, jmp3, jmp4, jmp5; int ckUniq = sqlite3VdbeMakeLabel(pParse); if( pPk==pIdx ) continue; r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3, pPrior, r1); pPrior = pIdx; sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);\/* increment entry count *\/ \/* Verify that an index entry exists for the current table row *\/ jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, pIdx->nColumn); VdbeCoverage(v); sqlite3VdbeLoadString(v, 3, \"row \"); sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); sqlite3VdbeLoadString(v, 4, \" missing from index \"); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); jmp4 = integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, jmp2); \/* For UNIQUE indexes, verify that only one entry exists with the ** current key. The entry is unique if (1) any column is NULL ** or (2) the next entry has a different key *\/ if( IsUniqueIndex(pIdx) ){ int uniqOk = sqlite3VdbeMakeLabel(pParse); int jmp6; int kk; for(kk=0; kknKeyCol; kk++){ int iCol = pIdx->aiColumn[kk]; assert( iCol!=XN_ROWID && iColnCol ); if( iCol>=0 && pTab->aCol[iCol].notNull ) continue; sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk); VdbeCoverage(v); } jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v); sqlite3VdbeGoto(v, uniqOk); sqlite3VdbeJumpHere(v, jmp6); sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1, pIdx->nKeyCol); VdbeCoverage(v); sqlite3VdbeLoadString(v, 3, \"non-unique entry in index \"); sqlite3VdbeGoto(v, jmp5); sqlite3VdbeResolveLabel(v, uniqOk); } sqlite3VdbeJumpHere(v, jmp4); sqlite3ResolvePartIdxLabel(pParse, jmp3); } } sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v); sqlite3VdbeJumpHere(v, loopTop-1); #ifndef SQLITE_OMIT_BTREECOUNT if( !isQuick ){ sqlite3VdbeLoadString(v, 2, \"wrong # of entries in index \"); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ if( pPk==pIdx ) continue; sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); sqlite3VdbeLoadString(v, 4, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3); integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, addr); } } #endif \/* SQLITE_OMIT_BTREECOUNT *\/ } } { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList endCode[] = { { OP_AddImm, 1, 0, 0}, \/* 0 *\/ { OP_IfNotZero, 1, 4, 0}, \/* 1 *\/ { OP_String8, 0, 3, 0}, \/* 2 *\/ { OP_ResultRow, 3, 1, 0}, \/* 3 *\/ { OP_Halt, 0, 0, 0}, \/* 4 *\/ { OP_String8, 0, 3, 0}, \/* 5 *\/ { OP_Goto, 0, 3, 0}, \/* 6 *\/ }; VdbeOp *aOp; aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn); if( aOp ){ aOp[0].p2 = 1-mxErr; aOp[2].p4type = P4_STATIC; aOp[2].p4.z = \"ok\"; aOp[5].p4type = P4_STATIC; aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT); } sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2); } } break; #endif \/* SQLITE_OMIT_INTEGRITY_CHECK *\/ #ifndef SQLITE_OMIT_UTF16 \/* ** PRAGMA encoding ** PRAGMA encoding = \"utf-8\"|\"utf-16\"|\"utf-16le\"|\"utf-16be\" ** ** In its first form, this pragma returns the encoding of the main ** database. If the database is not initialized, it is initialized now. ** ** The second form of this pragma is a no-op if the main database file ** has not already been initialized. In this case it sets the default ** encoding that will be used for the main database file if a new file ** is created. If an existing main database file is opened, then the ** default text encoding for the existing database is used. ** ** In all cases new databases created using the ATTACH command are ** created to use the same default text encoding as the main database. If ** the main database has not been initialized and\/or created when ATTACH ** is executed, this is done before the ATTACH operation. ** ** In the second form this pragma sets the text encoding to be used in ** new database files created using this database handle. It is only ** useful if invoked immediately after the main database i *\/ case PragTyp_ENCODING: { static const struct EncName { char *zName; u8 enc; } encnames[] = { { \"UTF8\", SQLITE_UTF8 }, { \"UTF-8\", SQLITE_UTF8 }, \/* Must be element [1] *\/ { \"UTF-16le\", SQLITE_UTF16LE }, \/* Must be element [2] *\/ { \"UTF-16be\", SQLITE_UTF16BE }, \/* Must be element [3] *\/ { \"UTF16le\", SQLITE_UTF16LE }, { \"UTF16be\", SQLITE_UTF16BE }, { \"UTF-16\", 0 }, \/* SQLITE_UTF16NATIVE *\/ { \"UTF16\", 0 }, \/* SQLITE_UTF16NATIVE *\/ { 0, 0 } }; const struct EncName *pEnc; if( !zRight ){ \/* \"PRAGMA encoding\" *\/ if( sqlite3ReadSchema(pParse) ) goto pragma_out; assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); returnSingleText(v, encnames[ENC(pParse->db)].zName); }else{ \/* \"PRAGMA encoding = XXX\" *\/ \/* Only change the value of sqlite.enc if the database handle is not ** initialized. If the main database exists, the new sqlite.enc value ** will be overwritten when the schema is next loaded. If it does not ** already exists, it will be created to use the new encoding value. *\/ if( !(DbHasProperty(db, 0, DB_SchemaLoaded)) || DbHasProperty(db, 0, DB_Empty) ){ for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ SCHEMA_ENC(db) = ENC(db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; break; } } if( !pEnc->zName ){ sqlite3ErrorMsg(pParse, \"unsupported encoding: %s\", zRight); } } } } break; #endif \/* SQLITE_OMIT_UTF16 *\/ #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS \/* ** PRAGMA [schema.]schema_version ** PRAGMA [schema.]schema_version = ** ** PRAGMA [schema.]user_version ** PRAGMA [schema.]user_version = ** ** PRAGMA [schema.]freelist_count ** ** PRAGMA [schema.]data_version ** ** PRAGMA [schema.]application_id ** PRAGMA [schema.]application_id = ** ** The pragma's schema_version and user_version are used to set or get ** the value of the schema-version and user-version, respectively. Both ** the schema-version and the user-version are 32-bit signed integers ** stored in the database header. ** ** The schema-cookie is usually only manipulated internally by SQLite. It ** is incremented by SQLite whenever the database schema is modified (by ** creating or dropping a table or index). The schema version is used by ** SQLite each time a query is executed to ensure that the internal cache ** of the schema used when compiling the SQL query matches the schema of ** the database against which the compiled query is actually executed. ** Subverting this mechanism by using \"PRAGMA schema_version\" to modify ** the schema-version is potentially dangerous and may lead to program ** crashes or database corruption. Use with caution! ** ** The user-version is not used internally by SQLite. It may be used by ** applications for any purpose. *\/ case PragTyp_HEADER_VALUE: { int iCookie = pPragma->iArg; \/* Which cookie to read or write *\/ sqlite3VdbeUsesBtree(v, iDb); if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){ \/* Write the specified cookie value *\/ static const VdbeOpList setCookie[] = { { OP_Transaction, 0, 1, 0}, \/* 0 *\/ { OP_SetCookie, 0, 0, 0}, \/* 1 *\/ }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p2 = iCookie; aOp[1].p3 = sqlite3Atoi(zRight); }else{ \/* Read the specified cookie value *\/ static const VdbeOpList readCookie[] = { { OP_Transaction, 0, 0, 0}, \/* 0 *\/ { OP_ReadCookie, 0, 1, 0}, \/* 1 *\/ { OP_ResultRow, 1, 1, 0} }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p3 = iCookie; sqlite3VdbeReusable(v); } } break; #endif \/* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS *\/ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS \/* ** PRAGMA compile_options ** ** Return the names of all compile-time options used in this build, ** one option per row. *\/ case PragTyp_COMPILE_OPTIONS: { int i = 0; const char *zOpt; pParse->nMem = 1; while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ sqlite3VdbeLoadString(v, 1, zOpt); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } sqlite3VdbeReusable(v); } break; #endif \/* SQLITE_OMIT_COMPILEOPTION_DIAGS *\/ #ifndef SQLITE_OMIT_WAL \/* ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate ** ** Checkpoint the database. *\/ case PragTyp_WAL_CHECKPOINT: { int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); int eMode = SQLITE_CHECKPOINT_PASSIVE; if( zRight ){ if( sqlite3StrICmp(zRight, \"full\")==0 ){ eMode = SQLITE_CHECKPOINT_FULL; }else if( sqlite3StrICmp(zRight, \"restart\")==0 ){ eMode = SQLITE_CHECKPOINT_RESTART; }else if( sqlite3StrICmp(zRight, \"truncate\")==0 ){ eMode = SQLITE_CHECKPOINT_TRUNCATE; } } pParse->nMem = 3; sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } break; \/* ** PRAGMA wal_autocheckpoint ** PRAGMA wal_autocheckpoint = N ** ** Configure a database connection to automatically checkpoint a database ** after accumulating N frames in the log. Or query for the current value ** of N. *\/ case PragTyp_WAL_AUTOCHECKPOINT: { if( zRight ){ sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); } returnSingleInt(v, db->xWalCallback==sqlite3WalDefaultHook ? SQLITE_PTR_TO_INT(db->pWalArg) : 0); } break; #endif \/* ** PRAGMA shrink_memory ** ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database ** connection on which it is invoked to free up as much memory as it ** can, by calling sqlite3_db_release_memory(). *\/ case PragTyp_SHRINK_MEMORY: { sqlite3_db_release_memory(db); break; } \/* ** PRAGMA optimize ** PRAGMA optimize(MASK) ** PRAGMA schema.optimize ** PRAGMA schema.optimize(MASK) ** ** Attempt to optimize the database. All schemas are optimized in the first ** two forms, and only the specified schema is optimized in the latter two. ** ** The details of optimizations performed by this pragma are expected ** to change and improve over time. Applications should anticipate that ** this pragma will perform new optimizations in future releases. ** ** The optional argument is a bitmask of optimizations to perform: ** ** 0x0001 Debugging mode. Do not actually perform any optimizations ** but instead return one line of text for each optimization ** that would have been done. Off by default. ** ** 0x0002 Run ANALYZE on tables that might benefit. On by default. ** See below for additional information. ** ** 0x0004 (Not yet implemented) Record usage and performance ** information from the current session in the ** database file so that it will be available to \"optimize\" ** pragmas run by future database connections. ** ** 0x0008 (Not yet implemented) Create indexes that might have ** been helpful to recent queries ** ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all ** of the optimizations listed above except Debug Mode, including new ** optimizations that have not yet been invented. If new optimizations are ** ever added that should be off by default, those off-by-default ** optimizations will have bitmasks of 0x10000 or larger. ** ** DETERMINATION OF WHEN TO RUN ANALYZE ** ** In the current implementation, a table is analyzed if only if all of ** the following are true: ** ** (1) MASK bit 0x02 is set. ** ** (2) The query planner used sqlite_stat1-style statistics for one or ** more indexes of the table at some point during the lifetime of ** the current connection. ** ** (3) One or more indexes of the table are currently unanalyzed OR ** the number of rows in the table has increased by 25 times or more ** since the last time ANALYZE was run. ** ** The rules for when tables are analyzed are likely to change in ** future releases. *\/ case PragTyp_OPTIMIZE: { int iDbLast; \/* Loop termination point for the schema loop *\/ int iTabCur; \/* Cursor for a table whose size needs checking *\/ HashElem *k; \/* Loop over tables of a schema *\/ Schema *pSchema; \/* The current schema *\/ Table *pTab; \/* A table in the schema *\/ Index *pIdx; \/* An index of the table *\/ LogEst szThreshold; \/* Size threshold above which reanalysis is needd *\/ char *zSubSql; \/* SQL statement for the OP_SqlExec opcode *\/ u32 opMask; \/* Mask of operations to perform *\/ if( zRight ){ opMask = (u32)sqlite3Atoi(zRight); if( (opMask & 0x02)==0 ) break; }else{ opMask = 0xfffe; } iTabCur = pParse->nTab++; for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){ if( iDb==1 ) continue; sqlite3CodeVerifySchema(pParse, iDb); pSchema = db->aDb[iDb].pSchema; for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ pTab = (Table*)sqliteHashData(k); \/* If table pTab has not been used in a way that would benefit from ** having analysis statistics during the current session, then skip it. ** This also has the effect of skipping virtual tables and views *\/ if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue; \/* Reanalyze if the table is 25 times larger than the last analysis *\/ szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 ); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( !pIdx->hasStat1 ){ szThreshold = 0; \/* Always analyze if any index lacks statistics *\/ break; } } if( szThreshold ){ sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold); VdbeCoverage(v); } zSubSql = sqlite3MPrintf(db, \"ANALYZE \\\"%w\\\".\\\"%w\\\"\", db->aDb[iDb].zDbSName, pTab->zName); if( opMask & 0x01 ){ int r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC); sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1); }else{ sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC); } } } sqlite3VdbeAddOp0(v, OP_Expire); break; } \/* ** PRAGMA busy_timeout ** PRAGMA busy_timeout = N ** ** Call sqlite3_busy_timeout(db, N). Return the current timeout value ** if one is set. If no busy handler or a different busy handler is set ** then 0 is returned. Setting the busy_timeout to 0 or negative ** disables the timeout. *\/ \/*case PragTyp_BUSY_TIMEOUT*\/ default: { assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT ); if( zRight ){ sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); } returnSingleInt(v, db->busyTimeout); break; } \/* ** PRAGMA soft_heap_limit ** PRAGMA soft_heap_limit = N ** ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the ** sqlite3_soft_heap_limit64() interface with the argument N, if N is ** specified and is a non-negative integer. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always ** returns the same integer that would be returned by the ** sqlite3_soft_heap_limit64(-1) C-language function. *\/ case PragTyp_SOFT_HEAP_LIMIT: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ sqlite3_soft_heap_limit64(N); } returnSingleInt(v, sqlite3_soft_heap_limit64(-1)); break; } \/* ** PRAGMA hard_heap_limit ** PRAGMA hard_heap_limit = N ** ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap ** limit. The hard heap limit can be activated or lowered by this ** pragma, but not raised or deactivated. Only the ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate ** the hard heap limit. This allows an application to set a heap limit ** constraint that cannot be relaxed by an untrusted SQL script. *\/ case PragTyp_HARD_HEAP_LIMIT: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1); if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N); } returnSingleInt(v, sqlite3_hard_heap_limit64(-1)); break; } \/* ** PRAGMA threads ** PRAGMA threads = N ** ** Configure the maximum number of worker threads. Return the new ** maximum, which might be less than requested. *\/ case PragTyp_THREADS: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK && N>=0 ){ sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff)); } returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1)); break; } #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) \/* ** Report the current state of file logs for all databases *\/ case PragTyp_LOCK_STATUS: { static const char *const azLockName[] = { \"unlocked\", \"shared\", \"reserved\", \"pending\", \"exclusive\" }; int i; pParse->nMem = 2; for(i=0; inDb; i++){ Btree *pBt; const char *zState = \"unknown\"; int j; if( db->aDb[i].zDbSName==0 ) continue; pBt = db->aDb[i].pBt; if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ zState = \"closed\"; }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ zState = azLockName[j]; } sqlite3VdbeMultiLoad(v, 1, \"ss\", db->aDb[i].zDbSName, zState); } break; } #endif #ifdef SQLITE_HAS_CODEC \/* Pragma iArg ** ---------- ------ ** key 0 ** rekey 1 ** hexkey 2 ** hexrekey 3 ** textkey 4 ** textrekey 5 *\/ case PragTyp_KEY: { if( zRight ){ char zBuf[40]; const char *zKey = zRight; int n; if( pPragma->iArg==2 || pPragma->iArg==3 ){ u8 iByte; int i; for(i=0, iByte=0; iiArg<4 ? sqlite3Strlen30(zRight) : -1; } if( (pPragma->iArg & 1)==0 ){ rc = sqlite3_key_v2(db, zDb, zKey, n); }else{ rc = sqlite3_rekey_v2(db, zDb, zKey, n); } if( rc==SQLITE_OK && n!=0 ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"ok\", SQLITE_STATIC); returnSingleText(v, \"ok\"); } } break; } #endif #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){ #ifdef SQLITE_HAS_CODEC if( sqlite3StrNICmp(zRight, \"see-\", 4)==0 ){ sqlite3_activate_see(&zRight[4]); } #endif #ifdef SQLITE_ENABLE_CEROD if( sqlite3StrNICmp(zRight, \"cerod-\", 6)==0 ){ sqlite3_activate_cerod(&zRight[6]); } #endif } break; #endif } \/* End of the PRAGMA switch *\/ \/* The following block is a no-op unless SQLITE_DEBUG is defined. Its only ** purpose is to execute assert() statements to verify that if the ** PragFlg_NoColumns1 flag is set and the caller specified an argument ** to the PRAGMA, the implementation has not added any OP_ResultRow ** instructions to the VM. *\/ if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){ sqlite3VdbeVerifyNoResultRow(v); } pragma_out: sqlite3DbFree(db, zLeft); sqlite3DbFree(db, zRight); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":42759,"input":"void CLASS identify() { char head[32], *cp; int hlen, flen, fsize, zero_fsize=1, i, c, is_canon; struct jhead jh; short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 } }; static const struct { int fsize; const char make[12], model[19], withjpeg; } table[] = { { 62464, \"Kodak\", \"DC20\" ,0 }, { 124928, \"Kodak\", \"DC20\" ,0 }, { 1652736, \"Kodak\", \"DCS200\" ,0 }, { 4159302, \"Kodak\", \"C330\" ,0 }, { 4162462, \"Kodak\", \"C330\" ,0 }, { 460800, \"Kodak\", \"C603v\" ,0 }, { 614400, \"Kodak\", \"C603v\" ,0 }, { 6163328, \"Kodak\", \"C603\" ,0 }, { 6166488, \"Kodak\", \"C603\" ,0 }, { 9116448, \"Kodak\", \"C603y\" ,0 }, { 311696, \"ST Micro\", \"STV680 VGA\" ,0 }, \/* SPYz *\/ { 787456, \"Creative\", \"PC-CAM 600\" ,0 }, { 1138688, \"Minolta\", \"RD175\" ,0 }, { 3840000, \"Foculus\", \"531C\" ,0 }, { 786432, \"AVT\", \"F-080C\" ,0 }, { 1447680, \"AVT\", \"F-145C\" ,0 }, { 1920000, \"AVT\", \"F-201C\" ,0 }, { 5067304, \"AVT\", \"F-510C\" ,0 }, { 5067316, \"AVT\", \"F-510C\" ,0 }, { 10134608, \"AVT\", \"F-510C\" ,0 }, { 10134620, \"AVT\", \"F-510C\" ,0 }, { 16157136, \"AVT\", \"F-810C\" ,0 }, { 1409024, \"Sony\", \"XCD-SX910CR\" ,0 }, { 2818048, \"Sony\", \"XCD-SX910CR\" ,0 }, { 3884928, \"Micron\", \"2010\" ,0 }, { 6624000, \"Pixelink\", \"A782\" ,0 }, { 13248000, \"Pixelink\", \"A782\" ,0 }, { 6291456, \"RoverShot\",\"3320AF\" ,0 }, { 6553440, \"Canon\", \"PowerShot A460\" ,0 }, { 6653280, \"Canon\", \"PowerShot A530\" ,0 }, { 6573120, \"Canon\", \"PowerShot A610\" ,0 }, { 9219600, \"Canon\", \"PowerShot A620\" ,0 }, { 9243240, \"Canon\", \"PowerShot A470\" ,0 }, { 10341600, \"Canon\", \"PowerShot A720 IS\",0 }, { 10383120, \"Canon\", \"PowerShot A630\" ,0 }, { 12945240, \"Canon\", \"PowerShot A640\" ,0 }, { 15636240, \"Canon\", \"PowerShot A650\" ,0 }, { 5298000, \"Canon\", \"PowerShot SD300\" ,0 }, { 7710960, \"Canon\", \"PowerShot S3 IS\" ,0 }, { 15467760, \"Canon\", \"PowerShot SX110 IS\",0 }, { 15534576, \"Canon\", \"PowerShot SX120 IS\",0 }, { 18653760, \"Canon\", \"PowerShot SX20 IS\",0 }, { 21936096, \"Canon\", \"PowerShot SX30 IS\",0 }, { 5939200, \"OLYMPUS\", \"C770UZ\" ,0 }, { 1581060, \"NIKON\", \"E900\" ,1 }, \/* or E900s,E910 *\/ { 2465792, \"NIKON\", \"E950\" ,1 }, \/* or E800,E700 *\/ { 2940928, \"NIKON\", \"E2100\" ,1 }, \/* or E2500 *\/ { 4771840, \"NIKON\", \"E990\" ,1 }, \/* or E995, Oly C3030Z *\/ { 4775936, \"NIKON\", \"E3700\" ,1 }, \/* or Optio 33WR *\/ { 5869568, \"NIKON\", \"E4300\" ,1 }, \/* or DiMAGE Z2 *\/ { 5865472, \"NIKON\", \"E4500\" ,1 }, { 7438336, \"NIKON\", \"E5000\" ,1 }, \/* or E5700 *\/ { 8998912, \"NIKON\", \"COOLPIX S6\" ,1 }, { 1976352, \"CASIO\", \"QV-2000UX\" ,1 }, { 3217760, \"CASIO\", \"QV-3*00EX\" ,1 }, { 6218368, \"CASIO\", \"QV-5700\" ,1 }, { 6054400, \"CASIO\", \"QV-R41\" ,1 }, { 7530816, \"CASIO\", \"QV-R51\" ,1 }, { 7684000, \"CASIO\", \"QV-4000\" ,1 }, { 2937856, \"CASIO\", \"EX-S20\" ,1 }, { 4948608, \"CASIO\", \"EX-S100\" ,1 }, { 7542528, \"CASIO\", \"EX-Z50\" ,1 }, { 7562048, \"CASIO\", \"EX-Z500\" ,1 }, { 7753344, \"CASIO\", \"EX-Z55\" ,1 }, { 7816704, \"CASIO\", \"EX-Z60\" ,1 }, { 10843712, \"CASIO\", \"EX-Z75\" ,1 }, { 10834368, \"CASIO\", \"EX-Z750\" ,1 }, { 12310144, \"CASIO\", \"EX-Z850\" ,1 }, { 15499264, \"CASIO\", \"EX-Z1050\" ,1 }, { 7426656, \"CASIO\", \"EX-P505\" ,1 }, { 9313536, \"CASIO\", \"EX-P600\" ,1 }, { 10979200, \"CASIO\", \"EX-P700\" ,1 }, { 3178560, \"PENTAX\", \"Optio S\" ,1 }, { 4841984, \"PENTAX\", \"Optio S\" ,1 }, { 6114240, \"PENTAX\", \"Optio S4\" ,1 }, \/* or S4i, CASIO EX-Z4 *\/ { 10702848, \"PENTAX\", \"Optio 750Z\" ,1 }, { 15980544, \"AGFAPHOTO\",\"DC-833m\" ,1 }, { 16098048, \"SAMSUNG\", \"S85\" ,1 }, { 16215552, \"SAMSUNG\", \"S85\" ,1 }, { 20487168, \"SAMSUNG\", \"WB550\" ,1 }, { 24000000, \"SAMSUNG\", \"WB550\" ,1 }, { 12582980, \"Sinar\", \"\" ,0 }, { 33292868, \"Sinar\", \"\" ,0 }, { 44390468, \"Sinar\", \"\" ,0 } }; static const char *corp[] = { \"Canon\", \"NIKON\", \"EPSON\", \"KODAK\", \"Kodak\", \"OLYMPUS\", \"PENTAX\", \"MINOLTA\", \"Minolta\", \"Konica\", \"CASIO\", \"Sinar\", \"Phase One\", \"SAMSUNG\", \"Mamiya\", \"MOTOROLA\" }; tiff_flip = flip = filters = -1; \/* 0 is valid, so -1 is unknown *\/ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = INT_MAX; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x4000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); fread (head, 1, 32, ifp); fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); \/* Note for Rawstudio maintainers, this check is not present in upstream dcraw *\/ if (fsize < 32) return; if ((cp = (char *) memmem (head, 32, \"MMMM\", 4)) || (cp = (char *) memmem (head, 32, \"IIII\", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,\"HEAPCCDR\",8)) { data_offset = hlen; parse_ciff (hlen, flen - hlen); } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,\"\\xff\\xd8\\xff\\xe1\",4) && !memcmp (head+6,\"Exif\",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,\"ARECOYK\",7)) { strcpy (make, \"Contax\"); strcpy (model,\"N Digital\"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 60, SEEK_SET); FORC4 cam_mul[c ^ (c >> 1)] = get4(); } else if (!strcmp (head, \"PXN\")) { strcpy (make, \"Logitech\"); strcpy (model,\"Fotoman Pixtura\"); } else if (!strcmp (head, \"qktk\")) { strcpy (make, \"Apple\"); strcpy (model,\"QuickTake 100\"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, \"qktn\")) { strcpy (make, \"Apple\"); strcpy (model,\"QuickTake 150\"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,\"FUJIFILM\",8)) { fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4()) && 1; if (is_raw == 2 && shot_select) parse_fuji (i); } fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,\"RIFF\",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head,\"\\0\\001\\0\\001\\0@\",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,\"NOKIARAW\",8)) { strcpy (make, \"NOKIA\"); strcpy (model, \"X2\"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); data_offset += i - width * 5 \/ 4 * height; load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,\"ARRI\",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, \"ARRI\"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head+4,\"RED1\",4)) { strcpy (make, \"RED\"); strcpy (model,\"ONE\"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1\/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,\"DSC-Image\",9)) parse_rollei(); else if (!memcmp (head,\"PWAD\",4)) parse_sinar_ia(); else if (!memcmp (head,\"\\0MRM\",4)) parse_minolta(0); else if (!memcmp (head,\"FOVb\",4)) parse_foveon(); else if (!memcmp (head,\"CI\",2)) parse_cine(); else for (zero_fsize=i=0; i < (int) sizeof table \/ (int) sizeof *table; i++) if (fsize == table[i].fsize) { strcpy (make, table[i].make ); strcpy (model, table[i].model); if (table[i].withjpeg) parse_external_jpeg(); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) parse_jpeg (is_raw = 0); for (i=0; i < (int) sizeof corp \/ (int) sizeof *corp; i++) if (strstr (make, corp[i])) \/* Simplify company names *\/ strcpy (make, corp[i]); if (!strncmp (make,\"KODAK\",5) && ((cp = strstr(model,\" DIGITAL CAMERA\")) || (cp = strstr(model,\" Digital Camera\")) || (cp = strstr(model,\"FILE VERSION\")))) *cp = 0; cp = make + strlen(make); \/* Remove trailing spaces *\/ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; i = strlen(make); \/* Remove make from model *\/ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,\"Digital Camera \",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (fuji_width) { fuji_width = (raw_width+1)\/2; width = height + fuji_width; height = width - 1; pixel_aspect = 1; } if (height == 2624 && width == 3936) \/* Pentax K10D and Samsung GX10 *\/ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) \/* Pentax K20D and Samsung GX20 *\/ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,\"K-r\") || !strcmp(model,\"K-x\"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strcmp(model,\"K-5\")) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 4736 && !strcmp(model,\"K-7\")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 7424 && !strcmp(model,\"645D\")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) \/* Ricoh GX200 *\/ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw = tiff_samples; else colors = tiff_samples; if (tiff_compress == 1) load_raw = &CLASS adobe_dng_load_raw_nc; if (tiff_compress == 7) load_raw = &CLASS adobe_dng_load_raw_lj; goto dng_skip; } if ((is_canon = !strcmp(make,\"Canon\"))) load_raw = memcmp (head+6,\"HEAPCCDR\",8) ? &CLASS lossless_jpeg_load_raw : &CLASS canon_compressed_load_raw; if (!strcmp(make,\"NIKON\")) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } if (!strcmp(make,\"CASIO\")) { load_raw = &CLASS packed_load_raw; maximum = 0xf7f; } \/* Set parameters based on camera name (for non-DNG files). *\/ if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; load_raw = &CLASS foveon_load_raw; simple_coeff(0); } else if (is_canon && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } filters = 0; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,\"PowerShot 600\")) { height = 613; width = 854; raw_width = 896; pixel_aspect = 607\/628.0; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,\"PowerShot A5\") || !strcmp(model,\"PowerShot A5 Zoom\")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256\/235.0; colors = 4; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,\"PowerShot A50\")) { height = 968; width = 1290; raw_width = 1320; colors = 4; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,\"PowerShot Pro70\")) { height = 1024; width = 1552; colors = 4; filters = 0x1e4b4e1b; goto canon_a5; } else if (!strcmp(model,\"PowerShot SD300\")) { height = 1752; width = 2344; raw_height = 1766; raw_width = 2400; top_margin = 12; left_margin = 12; goto canon_a5; } else if (!strcmp(model,\"PowerShot A460\")) { height = 1960; width = 2616; raw_height = 1968; raw_width = 2664; top_margin = 4; left_margin = 4; goto canon_a5; } else if (!strcmp(model,\"PowerShot A530\")) { height = 1984; width = 2620; raw_height = 1992; raw_width = 2672; top_margin = 6; left_margin = 10; goto canon_a5; } else if (!strcmp(model,\"PowerShot A610\")) { if (canon_s2is()) strcpy (model+10, \"S2 IS\"); height = 1960; width = 2616; raw_height = 1968; raw_width = 2672; top_margin = 8; left_margin = 12; goto canon_a5; } else if (!strcmp(model,\"PowerShot A620\")) { height = 2328; width = 3112; raw_height = 2340; raw_width = 3152; top_margin = 12; left_margin = 36; goto canon_a5; } else if (!strcmp(model,\"PowerShot A470\")) { height = 2328; width = 3096; raw_height = 2346; raw_width = 3152; top_margin = 6; left_margin = 12; goto canon_a5; } else if (!strcmp(model,\"PowerShot A720 IS\")) { height = 2472; width = 3298; raw_height = 2480; raw_width = 3336; top_margin = 5; left_margin = 6; goto canon_a5; } else if (!strcmp(model,\"PowerShot A630\")) { height = 2472; width = 3288; raw_height = 2484; raw_width = 3344; top_margin = 6; left_margin = 12; goto canon_a5; } else if (!strcmp(model,\"PowerShot A640\")) { height = 2760; width = 3672; raw_height = 2772; raw_width = 3736; top_margin = 6; left_margin = 12; goto canon_a5; } else if (!strcmp(model,\"PowerShot A650\")) { height = 3024; width = 4032; raw_height = 3048; raw_width = 4104; top_margin = 12; left_margin = 48; goto canon_a5; } else if (!strcmp(model,\"PowerShot S3 IS\")) { height = 2128; width = 2840; raw_height = 2136; raw_width = 2888; top_margin = 8; left_margin = 44; canon_a5: tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; if (raw_width > 1600) zero_is_bad = 1; } else if (!strcmp(model,\"PowerShot SX110 IS\")) { height = 2760; width = 3684; raw_height = 2772; raw_width = 3720; top_margin = 12; left_margin = 6; load_raw = &CLASS packed_load_raw; load_flags = 40; zero_is_bad = 1; } else if (!strcmp(model,\"PowerShot SX120 IS\")) { height = 2742; width = 3664; raw_height = 2778; raw_width = 3728; top_margin = 18; left_margin = 16; filters = 0x49494949; load_raw = &CLASS packed_load_raw; load_flags = 40; zero_is_bad = 1; } else if (!strcmp(model,\"PowerShot SX20 IS\")) { height = 3024; width = 4032; raw_height = 3048; raw_width = 4080; top_margin = 12; left_margin = 24; load_raw = &CLASS packed_load_raw; load_flags = 40; zero_is_bad = 1; } else if (!strcmp(model,\"PowerShot SX30 IS\")) { height = 3254; width = 4366; raw_height = 3276; raw_width = 4464; top_margin = 10; left_margin = 25; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 40; zero_is_bad = 1; } else if (!strcmp(model,\"PowerShot Pro90 IS\")) { width = 1896; colors = 4; filters = 0xb4b4b4b4; } else if (is_canon && raw_width == 2144) { height = 1550; width = 2088; top_margin = 8; left_margin = 4; if (!strcmp(model,\"PowerShot G1\")) { colors = 4; filters = 0xb4b4b4b4; } } else if (is_canon && raw_width == 2224) { height = 1448; width = 2176; top_margin = 6; left_margin = 48; } else if (is_canon && raw_width == 2376) { height = 1720; width = 2312; top_margin = 6; left_margin = 12; } else if (is_canon && raw_width == 2672) { height = 1960; width = 2616; top_margin = 6; left_margin = 12; } else if (is_canon && raw_width == 3152) { height = 2056; width = 3088; top_margin = 12; left_margin = 64; if (unique_id == 0x80000170) adobe_coeff (\"Canon\",\"EOS 300D\"); } else if (is_canon && raw_width == 3160) { height = 2328; width = 3112; top_margin = 12; left_margin = 44; } else if (is_canon && raw_width == 3344) { height = 2472; width = 3288; top_margin = 6; left_margin = 4; } else if (!strcmp(model,\"EOS D2000C\")) { filters = 0x61616161; black = curve[200]; } else if (is_canon && raw_width == 3516) { top_margin = 14; left_margin = 42; if (unique_id == 0x80000189) adobe_coeff (\"Canon\",\"EOS 350D\"); goto canon_cr2; } else if (is_canon && raw_width == 3596) { top_margin = 12; left_margin = 74; goto canon_cr2; } else if (is_canon && raw_width == 3744) { height = 2760; width = 3684; top_margin = 16; left_margin = 8; if (unique_id > 0x2720000) { top_margin = 12; left_margin = 52; } } else if (is_canon && raw_width == 3944) { height = 2602; width = 3908; top_margin = 18; left_margin = 30; } else if (is_canon && raw_width == 3948) { top_margin = 18; left_margin = 42; height -= 2; if (unique_id == 0x80000236) adobe_coeff (\"Canon\",\"EOS 400D\"); if (unique_id == 0x80000254) adobe_coeff (\"Canon\",\"EOS 1000D\"); goto canon_cr2; } else if (is_canon && raw_width == 3984) { top_margin = 20; left_margin = 76; height -= 2; goto canon_cr2; } else if (is_canon && raw_width == 4104) { height = 3024; width = 4032; top_margin = 12; left_margin = 48; } else if (is_canon && raw_width == 4152) { top_margin = 12; left_margin = 192; goto canon_cr2; } else if (is_canon && raw_width == 4160) { height = 3048; width = 4048; top_margin = 11; left_margin = 104; } else if (is_canon && raw_width == 4312) { top_margin = 18; left_margin = 22; height -= 2; if (unique_id == 0x80000176) adobe_coeff (\"Canon\",\"EOS 450D\"); goto canon_cr2; } else if (is_canon && raw_width == 4352) { top_margin = 18; left_margin = 62; if (unique_id == 0x80000288) adobe_coeff (\"Canon\",\"EOS 1100D\"); goto canon_cr2; } else if (is_canon && raw_width == 4476) { top_margin = 34; left_margin = 90; goto canon_cr2; } else if (is_canon && raw_width == 4480) { height = 3326; width = 4432; top_margin = 10; left_margin = 12; filters = 0x49494949; } else if (is_canon && raw_width == 4832) { top_margin = unique_id == 0x80000261 ? 51:26; left_margin = 62; if (unique_id == 0x80000252) adobe_coeff (\"Canon\",\"EOS 500D\"); goto canon_cr2; } else if (is_canon && raw_width == 5120) { height -= top_margin = 45; left_margin = 142; width = 4916; } else if (is_canon && raw_width == 5344) { top_margin = 51; left_margin = 142; if (unique_id == 0x80000270) adobe_coeff (\"Canon\",\"EOS 550D\"); if (unique_id == 0x80000286) adobe_coeff (\"Canon\",\"EOS 600D\"); goto canon_cr2; } else if (is_canon && raw_width == 5360) { top_margin = 51; left_margin = 158; goto canon_cr2; } else if (is_canon && raw_width == 5792) { top_margin = 51; left_margin = 158; goto canon_cr2; } else if (is_canon && raw_width == 5108) { top_margin = 13; left_margin = 98; canon_cr2: height -= top_margin; width -= left_margin; } else if (is_canon && raw_width == 5712) { height = 3752; width = 5640; top_margin = 20; left_margin = 62; } else if (!strcmp(model,\"D1\")) { cam_mul[0] *= 256\/527.0; cam_mul[2] *= 256\/317.0; } else if (!strcmp(model,\"D1X\")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,\"D40X\") || !strcmp(model,\"D60\") || !strcmp(model,\"D80\") || !strcmp(model,\"D3000\")) { height -= 3; width -= 4; } else if (!strcmp(model,\"D3\") || !strcmp(model,\"D3S\") || !strcmp(model,\"D700\")) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"D5000\")) { width -= 42; } else if (!strcmp(model,\"D5100\") || !strcmp(model,\"D7000\")) { width -= 44; } else if (!strcmp(model,\"D3100\")) { width -= 28; left_margin = 6; } else if (!strncmp(model,\"D40\",3) || !strncmp(model,\"D50\",3) || !strncmp(model,\"D70\",3)) { width--; } else if (!strcmp(model,\"D90\")) { width -= 42; } else if (!strcmp(model,\"D100\")) { if (tiff_compress == 34713 && !nikon_is_compressed()) { load_raw = &CLASS packed_load_raw; load_flags |= 1; raw_width = (width += 3) + 3; } } else if (!strcmp(model,\"D200\")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,\"D2H\",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,\"D2X\",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,\"D300\",4)) { width -= 32; } else if (!strncmp(model,\"COOLPIX P\",9)) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && iso_speed >= 400) black = 255; } else if (!strncmp(model,\"1 \",2)) { height -= 2; } else if (fsize == 1581060) { height = 963; width = 1287; raw_width = 1632; maximum = 0x3f4; colors = 4; filters = 0x1e1e1e1e; simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; goto e900; } else if (fsize == 2465792) { height = 1203; width = 1616; raw_width = 2048; colors = 4; filters = 0x4b4b4b4b; adobe_coeff (\"NIKON\",\"E950\"); e900: tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 6; } else if (fsize == 4771840) { height = 1540; width = 2064; colors = 4; filters = 0xe1e1e1e1; load_raw = &CLASS packed_load_raw; load_flags = 6; if (!timestamp && nikon_e995()) strcpy (model, \"E995\"); if (strcmp(model,\"E995\")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (!strcmp(model,\"E2100\")) { if (!timestamp && !nikon_e2100()) goto cp_e2500; height = 1206; width = 1616; load_flags = 30; } else if (!strcmp(model,\"E2500\")) { cp_e2500: strcpy (model, \"E2500\"); height = 1204; width = 1616; colors = 4; filters = 0x4b4b4b4b; } else if (fsize == 4775936) { height = 1542; width = 2064; load_raw = &CLASS packed_load_raw; load_flags = 30; if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,\"Optio 33WR\")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { height = 1710; width = 2288; filters = 0x16161616; if (!timestamp && minolta_z2()) { strcpy (make, \"Minolta\"); strcpy (model,\"DiMAGE Z2\"); } load_raw = &CLASS packed_load_raw; load_flags = 6 + 24*(make[0] == 'M'); } else if (!strcmp(model,\"E4500\")) { height = 1708; width = 2288; colors = 4; filters = 0xb4b4b4b4; } else if (fsize == 7438336) { height = 1924; width = 2576; colors = 4; filters = 0xb4b4b4b4; } else if (fsize == 8998912) { height = 2118; width = 2832; maximum = 0xf83; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strcmp(model,\"FinePix S5100\") || !strcmp(model,\"FinePix S5500\")) { height -= top_margin = 6; } else if (!strcmp(make,\"FUJIFILM\")) { if (!strcmp(model+7,\"S2Pro\")) { strcpy (model+7,\" S2Pro\"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 3328) { width = 3262; left_margin = 34; } if (!strcmp(model,\"X10\")) filters = 0x16161616; if (fuji_layout) raw_width *= is_raw; if (load_raw == &CLASS fuji_load_raw) { fuji_width = width >> !fuji_layout; width = (height >> fuji_layout) + fuji_width; raw_height = height; height = width - 1; if (~fuji_width & 1) filters = 0x49494949; } } else if (!strcmp(model,\"RD175\")) { height = 986; width = 1534; data_offset = 513; filters = 0x61616161; load_raw = &CLASS minolta_rd175_load_raw; } else if (!strcmp(model,\"KD-400Z\")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,\"KD-510Z\")) { goto konica_510z; } else if (!strcasecmp(make,\"MINOLTA\")) { load_raw = &CLASS unpacked_load_raw; maximum = 0xfff; if (!strncmp(model,\"DiMAGE A\",8)) { if (!strcmp(model,\"DiMAGE A200\")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,\"ALPHA\",5) || !strncmp(model,\"DYNAX\",5) || !strncmp(model,\"MAXXUM\",6)) { sprintf (model+20, \"DYNAX %-10s\", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,\"DiMAGE G\",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,\"*ist D\")) { data_error = -1; } else if (!strcmp(model,\"*ist DS\")) { height -= 2; } else if (!strcmp(model,\"Optio S\")) { if (fsize == 3178560) { height = 1540; width = 2064; load_raw = &CLASS eight_bit_load_raw; cam_mul[0] *= 4; cam_mul[2] *= 4; } else { height = 1544; width = 2068; raw_width = 3136; load_raw = &CLASS packed_load_raw; maximum = 0xf7c; } } else if (fsize == 6114240) { height = 1737; width = 2324; raw_width = 3520; load_raw = &CLASS packed_load_raw; maximum = 0xf7a; } else if (!strcmp(model,\"Optio 750Z\")) { height = 2302; width = 3072; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strcmp(model,\"DC-833m\")) { height = 2448; width = 3264; order = 0x4949; filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; maximum = 0xfc00; } else if (!strncmp(model,\"S85\",3)) { height = 2448; width = 3264; raw_width = fsize\/height\/2; order = 0x4d4d; load_raw = &CLASS unpacked_load_raw; } else if (!strncmp(model,\"NX1\",3)) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strcmp(model,\"NX200\")) { order = 0x4949; height = 3662; width = 5528; top_margin = 2; left_margin = 46; } else if (!strcmp(model,\"EX1\")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,\"WB2000\")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (fsize == 20487168) { height = 2808; width = 3648; goto wb550; } else if (fsize == 24000000) { height = 3000; width = 4000; wb550: strcpy (model, \"WB550\"); order = 0x4d4d; load_raw = &CLASS unpacked_load_raw; load_flags = 6; maximum = 0x3df; } else if (!strcmp(model,\"STV680 VGA\")) { height = 484; width = 644; load_raw = &CLASS eight_bit_load_raw; flip = 2; filters = 0x16161616; black = 16; } else if (!strcmp(model,\"N95\")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,\"531C\")) { height = 1200; width = 1600; load_raw = &CLASS unpacked_load_raw; filters = 0x49494949; } else if (!strcmp(model,\"F-080C\")) { height = 768; width = 1024; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,\"F-145C\")) { height = 1040; width = 1392; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,\"F-201C\")) { height = 1200; width = 1600; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,\"F-510C\")) { height = 1958; width = 2588; load_raw = fsize < 7500000 ? &CLASS eight_bit_load_raw : &CLASS unpacked_load_raw; data_offset = fsize - width*height*(fsize >> 22); maximum = 0xfff0; } else if (!strcmp(model,\"F-810C\")) { height = 2469; width = 3272; load_raw = &CLASS unpacked_load_raw; maximum = 0xfff0; } else if (!strcmp(model,\"XCD-SX910CR\")) { height = 1024; width = 1375; raw_width = 1376; filters = 0x49494949; maximum = 0x3ff; load_raw = fsize < 2000000 ? &CLASS eight_bit_load_raw : &CLASS unpacked_load_raw; } else if (!strcmp(model,\"2010\")) { height = 1207; width = 1608; order = 0x4949; filters = 0x16161616; data_offset = 3212; maximum = 0x3ff; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,\"A782\")) { height = 3000; width = 2208; filters = 0x61616161; load_raw = fsize < 10000000 ? &CLASS eight_bit_load_raw : &CLASS unpacked_load_raw; maximum = 0xffc0; } else if (!strcmp(model,\"3320AF\")) { height = 1536; raw_width = width = 2048; filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; maximum = 0x3ff; fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, \"ISG\"); model[0] = 0; } } else if (!strcmp(make,\"Hasselblad\")) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; } else if (raw_width == 7410) { height = 5502; width = 7328; top_margin = 4; left_margin = 41; filters = 0x61616161; } else if (raw_width == 9044) { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; } else if (raw_width == 4090) { strcpy (model, \"V96C\"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } } else if (!strcmp(make,\"Sinar\")) { if (!memcmp(head,\"8BPS\",4)) { fseek (ifp, 14, SEEK_SET); height = get4(); width = get4(); filters = 0x61616161; data_offset = 68; } if (!load_raw) load_raw = &CLASS unpacked_load_raw; maximum = 0x3fff; } else if (!strcmp(make,\"Leaf\")) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, \"RBTG\"); strcpy (model, \"CatchLight\"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, \"DCB2\"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, \"Cantare\"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, \"Valeo 6\"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, \"Valeo 6\"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strcmp(make,\"LEICA\") || !strcmp(make,\"Panasonic\")) { if ((flen - data_offset) \/ (raw_width*8\/7) == raw_height) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < (int) sizeof pana \/ (int) sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) \"\\x94\\x61\\x49\\x16\" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,\"C770UZ\")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strcmp(make,\"OLYMPUS\")) { height += height & 1; filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,\"E-300\") || !strcmp(model,\"E-500\")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,\"E-330\")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,\"SP550UZ\")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } } else if (!strcmp(model,\"N Digital\")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,\"DSC-F828\")) { width = 3288; left_margin = 5; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, \"RGBE\"); } else if (!strcmp(model,\"DSC-V3\")) { width = 3109; left_margin = 59; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strcmp(make,\"SONY\") && raw_width == 3984) { adobe_coeff (\"SONY\",\"DSC-R1\"); width = 3925; order = 0x4d4d; } else if (!strcmp(make,\"SONY\") && raw_width == 6048) { width -= 24; } else if (!strcmp(model,\"DSLR-A100\")) { if (width == 3880) { height--; width = ++raw_width; } else { order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,\"DSLR-A350\")) { height -= 4; } else if (!strcmp(model,\"NEX-5N\")) { width -= 24; } else if (!strcmp(model,\"PIXL\")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,\"C603v\")) { height = 480; width = 640; if (fsize < 614400 || find_green (16, 16, 3840, 5120) < 25) goto c603v; strcpy (model,\"KAI-0340\"); height -= 3; data_offset = 3840; order = 0x4949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,\"C603y\")) { height = 2134; width = 2848; c603v: filters = 0; load_raw = &CLASS kodak_yrgb_load_raw; gamma_curve (0, 3.875, 1, 255); } else if (!strcmp(model,\"C603\")) { raw_height = height = 2152; raw_width = width = 2864; goto c603; } else if (!strcmp(model,\"C330\")) { height = 1744; width = 2336; raw_height = 1779; raw_width = 2338; top_margin = 33; left_margin = 1; c603: order = 0x4949; if ((data_offset = fsize - raw_height*raw_width)) { fseek (ifp, 168, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = &CLASS eight_bit_load_raw; } else if (!strncasecmp(model,\"EasyShare\",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strcasecmp(make,\"KODAK\")) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,\"NC2000\",6)) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"EOSDCS3B\")) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"EOSDCS1\")) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"DCS420\")) { width -= 4; left_margin = 2; } else if (!strncmp(model,\"DCS460 \",7)) { model[6] = 0; width -= 4; left_margin = 2; } else if (!strcmp(model,\"DCS460A\")) { width -= 4; left_margin = 2; colors = 1; filters = 0; } else if (!strcmp(model,\"DCS660M\")) { black = 214; colors = 1; filters = 0; } else if (!strcmp(model,\"DCS760M\")) { colors = 1; filters = 0; } if (!strcmp(model+4,\"20X\")) strcpy (cdesc, \"MYCY\"); if (strstr(model,\"DC25\")) { strcpy (model, \"DC25\"); data_offset = 15424; } if (!strncmp(model,\"DC2\",3)) { height = 242; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) \/ (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) \/ (373.0*width); } data_offset += raw_width + 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,\"40\")) { strcpy (model, \"DC40\"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,\"DC50\")) { strcpy (model, \"DC50\"); height = 512; width = 768; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,\"DC120\")) { strcpy (model, \"DC120\"); height = 976; width = 848; pixel_aspect = height\/0.75\/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,\"DCS200\")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; write_thumb = &CLASS layer_thumb; height = 1024; width = 1536; data_offset = 79872; load_raw = &CLASS eight_bit_load_raw; black = 17; } } else if (!strcmp(model,\"Fotoman Pixtura\")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,\"QuickTake\",9)) { if (head[5]) strcpy (model+10, \"200\"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strcmp(make,\"Rollei\") && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,\"PC-CAM 600\")) { height = 768; data_offset = width = 1024; filters = 0x49494949; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,\"QV-2000UX\")) { height = 1208; width = 1632; data_offset = width * 2; load_raw = &CLASS eight_bit_load_raw; } else if (fsize == 3217760) { height = 1546; width = 2070; raw_width = 2080; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,\"QV-4000\")) { height = 1700; width = 2260; load_raw = &CLASS unpacked_load_raw; maximum = 0xffff; } else if (!strcmp(model,\"QV-5700\")) { height = 1924; width = 2576; raw_width = 3232; tiff_bps = 10; } else if (!strcmp(model,\"QV-R41\")) { height = 1720; width = 2312; raw_width = 3520; left_margin = 2; } else if (!strcmp(model,\"QV-R51\")) { height = 1926; width = 2580; raw_width = 3904; } else if (!strcmp(model,\"EX-S20\")) { height = 1208; width = 1620; raw_width = 2432; flip = 3; } else if (!strcmp(model,\"EX-S100\")) { height = 1544; width = 2058; raw_width = 3136; } else if (!strcmp(model,\"EX-Z50\")) { height = 1931; width = 2570; raw_width = 3904; } else if (!strcmp(model,\"EX-Z500\")) { height = 1937; width = 2577; raw_width = 3904; filters = 0x16161616; } else if (!strcmp(model,\"EX-Z55\")) { height = 1960; width = 2570; raw_width = 3904; } else if (!strcmp(model,\"EX-Z60\")) { height = 2145; width = 2833; raw_width = 3584; filters = 0x16161616; tiff_bps = 10; } else if (!strcmp(model,\"EX-Z75\")) { height = 2321; width = 3089; raw_width = 4672; maximum = 0xfff; } else if (!strcmp(model,\"EX-Z750\")) { height = 2319; width = 3087; raw_width = 4672; maximum = 0xfff; } else if (!strcmp(model,\"EX-Z850\")) { height = 2468; width = 3279; raw_width = 4928; maximum = 0xfff; } else if (fsize == 15499264) { \/* EX-Z1050 or EX-Z1080 *\/ height = 2752; width = 3672; raw_width = 5632; } else if (!strcmp(model,\"EX-P505\")) { height = 1928; width = 2568; raw_width = 3852; maximum = 0xfff; } else if (fsize == 9313536) { \/* EX-P600 or QV-R61 *\/ height = 2142; width = 2844; raw_width = 4288; } else if (!strcmp(model,\"EX-P700\")) { height = 2318; width = 3082; raw_width = 4672; } if (!model[0]) sprintf (model, \"%dx%d\", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (raw_color) adobe_coeff (make, model); if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff (\"Apple\",\"Quicktake\"); if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: if (!tiff_bps) tiff_bps = 12; if (!maximum) maximum = (1 << tiff_bps) - 1; if (!load_raw || height < 22) is_raw = 0; #ifndef HAVE_LIBJASPER if (load_raw == &CLASS redcine_load_raw) { dcraw_message (DCRAW_ERROR,_(\"%s: You must link dcraw with %s!!\\n\"), ifname_display, \"libjasper\"); is_raw = 0; } #endif #ifndef HAVE_LIBJPEG if (load_raw == &CLASS kodak_jpeg_load_raw) { dcraw_message (DCRAW_ERROR,_(\"%s: You must link dcraw with %s!!\\n\"), ifname_display, \"libjpeg\"); is_raw = 0; } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? \"RGBG\":\"GMCY\"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == -1) flip = tiff_flip; if (flip == -1) flip = 0; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":68155,"input":"static MagickBooleanType SetsRGBImageProfile(Image *image, ExceptionInfo *exception) { static unsigned char sRGBProfile[] = { 0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, 0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a, 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99, 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67, 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88, 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c, 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24, 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24, 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14, 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14, 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14, 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d, 0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00, 0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c, 0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2, 0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d, 0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0, 0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87, 0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20, 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24, 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40, 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76, 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4, 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d, 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae, 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a, 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff, 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce, 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7, 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba, 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8, 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10, 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff }; StringInfo *profile; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (GetImageProfile(image,\"icc\") != (const StringInfo *) NULL) return(MagickFalse); profile=AcquireStringInfo(sizeof(sRGBProfile)); SetStringInfoDatum(profile,sRGBProfile); status=SetImageProfile(image,\"icc\",profile,exception); profile=DestroyStringInfo(profile); return(status); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":3723,"input":"mrb_vm_exec(mrb_state *mrb, struct RProc *proc, mrb_code *pc) { \/* mrb_assert(mrb_proc_cfunc_p(proc)) *\/ mrb_irep *irep = proc->body.irep; mrb_value *pool = irep->pool; mrb_sym *syms = irep->syms; mrb_code i; int ai = mrb_gc_arena_save(mrb); struct mrb_jmpbuf *prev_jmp = mrb->jmp; struct mrb_jmpbuf c_jmp; #ifdef DIRECT_THREADED static void *optable[] = { &&L_OP_NOP, &&L_OP_MOVE, &&L_OP_LOADL, &&L_OP_LOADI, &&L_OP_LOADSYM, &&L_OP_LOADNIL, &&L_OP_LOADSELF, &&L_OP_LOADT, &&L_OP_LOADF, &&L_OP_GETGLOBAL, &&L_OP_SETGLOBAL, &&L_OP_GETSPECIAL, &&L_OP_SETSPECIAL, &&L_OP_GETIV, &&L_OP_SETIV, &&L_OP_GETCV, &&L_OP_SETCV, &&L_OP_GETCONST, &&L_OP_SETCONST, &&L_OP_GETMCNST, &&L_OP_SETMCNST, &&L_OP_GETUPVAR, &&L_OP_SETUPVAR, &&L_OP_JMP, &&L_OP_JMPIF, &&L_OP_JMPNOT, &&L_OP_ONERR, &&L_OP_RESCUE, &&L_OP_POPERR, &&L_OP_RAISE, &&L_OP_EPUSH, &&L_OP_EPOP, &&L_OP_SEND, &&L_OP_SENDB, &&L_OP_FSEND, &&L_OP_CALL, &&L_OP_SUPER, &&L_OP_ARGARY, &&L_OP_ENTER, &&L_OP_KARG, &&L_OP_KDICT, &&L_OP_RETURN, &&L_OP_TAILCALL, &&L_OP_BLKPUSH, &&L_OP_ADD, &&L_OP_ADDI, &&L_OP_SUB, &&L_OP_SUBI, &&L_OP_MUL, &&L_OP_DIV, &&L_OP_EQ, &&L_OP_LT, &&L_OP_LE, &&L_OP_GT, &&L_OP_GE, &&L_OP_ARRAY, &&L_OP_ARYCAT, &&L_OP_ARYPUSH, &&L_OP_AREF, &&L_OP_ASET, &&L_OP_APOST, &&L_OP_STRING, &&L_OP_STRCAT, &&L_OP_HASH, &&L_OP_LAMBDA, &&L_OP_RANGE, &&L_OP_OCLASS, &&L_OP_CLASS, &&L_OP_MODULE, &&L_OP_EXEC, &&L_OP_METHOD, &&L_OP_SCLASS, &&L_OP_TCLASS, &&L_OP_DEBUG, &&L_OP_STOP, &&L_OP_ERR, }; #endif mrb_bool exc_catched = FALSE; RETRY_TRY_BLOCK: MRB_TRY(&c_jmp) { if (exc_catched) { exc_catched = FALSE; if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK) goto L_BREAK; goto L_RAISE; } mrb->jmp = &c_jmp; mrb->c->ci->proc = proc; mrb->c->ci->nregs = irep->nregs; #define regs (mrb->c->stack) INIT_DISPATCH { CASE(OP_NOP) { \/* do nothing *\/ NEXT; } CASE(OP_MOVE) { \/* A B R(A) := R(B) *\/ int a = GETARG_A(i); int b = GETARG_B(i); regs[a] = regs[b]; NEXT; } CASE(OP_LOADL) { \/* A Bx R(A) := Pool(Bx) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); #ifdef MRB_WORD_BOXING mrb_value val = pool[bx]; #ifndef MRB_WITHOUT_FLOAT if (mrb_float_p(val)) { val = mrb_float_value(mrb, mrb_float(val)); } #endif regs[a] = val; #else regs[a] = pool[bx]; #endif NEXT; } CASE(OP_LOADI) { \/* A sBx R(A) := sBx *\/ int a = GETARG_A(i); mrb_int bx = GETARG_sBx(i); SET_INT_VALUE(regs[a], bx); NEXT; } CASE(OP_LOADSYM) { \/* A Bx R(A) := Syms(Bx) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); SET_SYM_VALUE(regs[a], syms[bx]); NEXT; } CASE(OP_LOADSELF) { \/* A R(A) := self *\/ int a = GETARG_A(i); regs[a] = regs[0]; NEXT; } CASE(OP_LOADT) { \/* A R(A) := true *\/ int a = GETARG_A(i); SET_TRUE_VALUE(regs[a]); NEXT; } CASE(OP_LOADF) { \/* A R(A) := false *\/ int a = GETARG_A(i); SET_FALSE_VALUE(regs[a]); NEXT; } CASE(OP_GETGLOBAL) { \/* A Bx R(A) := getglobal(Syms(Bx)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_gv_get(mrb, syms[bx]); regs[a] = val; NEXT; } CASE(OP_SETGLOBAL) { \/* A Bx setglobal(Syms(Bx), R(A)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_gv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETSPECIAL) { \/* A Bx R(A) := Special[Bx] *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_vm_special_get(mrb, bx); regs[a] = val; NEXT; } CASE(OP_SETSPECIAL) { \/* A Bx Special[Bx] := R(A) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_special_set(mrb, bx, regs[a]); NEXT; } CASE(OP_GETIV) { \/* A Bx R(A) := ivget(Bx) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_vm_iv_get(mrb, syms[bx]); regs[a] = val; NEXT; } CASE(OP_SETIV) { \/* A Bx ivset(Syms(Bx),R(A)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_iv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETCV) { \/* A Bx R(A) := cvget(Syms(Bx)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val; ERR_PC_SET(mrb, pc); val = mrb_vm_cv_get(mrb, syms[bx]); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETCV) { \/* A Bx cvset(Syms(Bx),R(A)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_cv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETCONST) { \/* A Bx R(A) := constget(Syms(Bx)) *\/ mrb_value val; int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_sym sym = syms[bx]; ERR_PC_SET(mrb, pc); val = mrb_vm_const_get(mrb, sym); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETCONST) { \/* A Bx constset(Syms(Bx),R(A)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_const_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETMCNST) { \/* A Bx R(A) := R(A)::Syms(Bx) *\/ mrb_value val; int a = GETARG_A(i); int bx = GETARG_Bx(i); ERR_PC_SET(mrb, pc); val = mrb_const_get(mrb, regs[a], syms[bx]); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETMCNST) { \/* A Bx R(A+1)::Syms(Bx) := R(A) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_const_set(mrb, regs[a+1], syms[bx], regs[a]); NEXT; } CASE(OP_GETUPVAR) { \/* A B C R(A) := uvget(B,C) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value *regs_a = regs + a; struct REnv *e = uvenv(mrb, c); if (!e) { *regs_a = mrb_nil_value(); } else { *regs_a = e->stack[b]; } NEXT; } CASE(OP_SETUPVAR) { \/* A B C uvset(B,C,R(A)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); struct REnv *e = uvenv(mrb, c); if (e) { mrb_value *regs_a = regs + a; if (b < MRB_ENV_STACK_LEN(e)) { e->stack[b] = *regs_a; mrb_write_barrier(mrb, (struct RBasic*)e); } } NEXT; } CASE(OP_JMP) { \/* sBx pc+=sBx *\/ int sbx = GETARG_sBx(i); pc += sbx; JUMP; } CASE(OP_JMPIF) { \/* A sBx if R(A) pc+=sBx *\/ int a = GETARG_A(i); int sbx = GETARG_sBx(i); if (mrb_test(regs[a])) { pc += sbx; JUMP; } NEXT; } CASE(OP_JMPNOT) { \/* A sBx if !R(A) pc+=sBx *\/ int a = GETARG_A(i); int sbx = GETARG_sBx(i); if (!mrb_test(regs[a])) { pc += sbx; JUMP; } NEXT; } CASE(OP_ONERR) { \/* sBx pc+=sBx on exception *\/ int sbx = GETARG_sBx(i); if (mrb->c->rsize <= mrb->c->ci->ridx) { if (mrb->c->rsize == 0) mrb->c->rsize = RESCUE_STACK_INIT_SIZE; else mrb->c->rsize *= 2; mrb->c->rescue = (mrb_code **)mrb_realloc(mrb, mrb->c->rescue, sizeof(mrb_code*) * mrb->c->rsize); } mrb->c->rescue[mrb->c->ci->ridx++] = pc + sbx; NEXT; } CASE(OP_RESCUE) { \/* A B R(A) := exc; clear(exc); R(B) := matched (bool) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value exc; if (c == 0) { exc = mrb_obj_value(mrb->exc); mrb->exc = 0; } else { \/* continued; exc taken from R(A) *\/ exc = regs[a]; } if (b != 0) { mrb_value e = regs[b]; struct RClass *ec; switch (mrb_type(e)) { case MRB_TT_CLASS: case MRB_TT_MODULE: break; default: { mrb_value exc; exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, \"class or module required for rescue clause\"); mrb_exc_set(mrb, exc); goto L_RAISE; } } ec = mrb_class_ptr(e); regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec)); } if (a != 0 && c == 0) { regs[a] = exc; } NEXT; } CASE(OP_POPERR) { \/* A A.times{rescue_pop()} *\/ int a = GETARG_A(i); mrb->c->ci->ridx -= a; NEXT; } CASE(OP_RAISE) { \/* A raise(R(A)) *\/ int a = GETARG_A(i); mrb_exc_set(mrb, regs[a]); goto L_RAISE; } CASE(OP_EPUSH) { \/* Bx ensure_push(SEQ[Bx]) *\/ int bx = GETARG_Bx(i); struct RProc *p; p = mrb_closure_new(mrb, irep->reps[bx]); \/* push ensure_stack *\/ if (mrb->c->esize <= mrb->c->eidx+1) { if (mrb->c->esize == 0) mrb->c->esize = ENSURE_STACK_INIT_SIZE; else mrb->c->esize *= 2; mrb->c->ensure = (struct RProc **)mrb_realloc(mrb, mrb->c->ensure, sizeof(struct RProc*) * mrb->c->esize); } mrb->c->ensure[mrb->c->eidx++] = p; mrb->c->ensure[mrb->c->eidx] = NULL; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EPOP) { \/* A A.times{ensure_pop().call} *\/ int a = GETARG_A(i); mrb_callinfo *ci = mrb->c->ci; int n, epos = ci->epos; mrb_value self = regs[0]; struct RClass *target_class = ci->target_class; if (mrb->c->eidx <= epos) { NEXT; } if (a > mrb->c->eidx - epos) a = mrb->c->eidx - epos; pc = pc + 1; for (n=0; nc->ensure[epos+n]; mrb->c->ensure[epos+n] = NULL; if (proc == NULL) continue; irep = proc->body.irep; ci = cipush(mrb); ci->mid = ci[-1].mid; ci->argc = 0; ci->proc = proc; ci->stackent = mrb->c->stack; ci->nregs = irep->nregs; ci->target_class = target_class; ci->pc = pc; ci->acc = ci[-1].nregs; mrb->c->stack += ci->acc; stack_extend(mrb, ci->nregs); regs[0] = self; pc = irep->iseq; } pool = irep->pool; syms = irep->syms; mrb->c->eidx = epos; JUMP; } CASE(OP_LOADNIL) { \/* A R(A) := nil *\/ int a = GETARG_A(i); SET_NIL_VALUE(regs[a]); NEXT; } CASE(OP_SENDB) { \/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C),&R(A+C+1))*\/ \/* fall through *\/ }; L_SEND: CASE(OP_SEND) { \/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C)) *\/ int a = GETARG_A(i); int n = GETARG_C(i); int argc = (n == CALL_MAXARGS) ? -1 : n; int bidx = (argc < 0) ? a+2 : a+n+1; mrb_method_t m; struct RClass *c; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; mrb_sym mid = syms[GETARG_B(i)]; mrb_assert(bidx < ci->nregs); recv = regs[a]; if (GET_OPCODE(i) != OP_SENDB) { SET_NIL_VALUE(regs[bidx]); blk = regs[bidx]; } else { blk = regs[bidx]; if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) { blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, \"Proc\", \"to_proc\"); \/* The stack might have been reallocated during mrb_convert_type(), see #3622 *\/ regs[bidx] = blk; } } c = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_sym missing = mrb_intern_lit(mrb, \"method_missing\"); m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m) || (missing == mrb->c->ci->mid && mrb_obj_eq(mrb, regs[0], recv))) { mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1); ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } if (argc >= 0) { if (a+2 >= irep->nregs) { stack_extend(mrb, a+3); } regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1); regs[a+2] = blk; argc = -1; } mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(mid)); mid = missing; } \/* push callinfo *\/ ci = cipush(mrb); ci->mid = mid; ci->stackent = mrb->c->stack; ci->target_class = c; ci->argc = argc; ci->pc = pc + 1; ci->acc = a; \/* prepare stack *\/ mrb->c->stack += a; if (MRB_METHOD_CFUNC_P(m)) { ci->nregs = (argc < 0) ? 3 : n+2; if (MRB_METHOD_PROC_P(m)) { struct RProc *p = MRB_METHOD_PROC(m); ci->proc = p; recv = p->body.func(mrb, recv); } else { recv = MRB_METHOD_FUNC(m)(mrb, recv); } mrb_gc_arena_restore(mrb, ai); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (GET_OPCODE(i) == OP_SENDB) { if (mrb_type(blk) == MRB_TT_PROC) { struct RProc *p = mrb_proc_ptr(blk); if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == ci[-1].env) { p->flags |= MRB_PROC_ORPHAN; } } } if (!ci->target_class) { \/* return from context modifying method (resume\/yield) *\/ if (ci->acc == CI_ACC_RESUMED) { mrb->jmp = prev_jmp; return recv; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->stack[0] = recv; \/* pop stackpos *\/ mrb->c->stack = ci->stackent; pc = ci->pc; cipop(mrb); JUMP; } else { \/* setup environment for calling method *\/ proc = ci->proc = MRB_METHOD_PROC(m); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs); pc = irep->iseq; JUMP; } } CASE(OP_FSEND) { \/* A B C R(A) := fcall(R(A),Syms(B),R(A+1),... ,R(A+C-1)) *\/ \/* not implemented yet *\/ NEXT; } CASE(OP_CALL) { \/* A R(A) := self.call(frame.argc, frame.argv) *\/ mrb_callinfo *ci; mrb_value recv = mrb->c->stack[0]; struct RProc *m = mrb_proc_ptr(recv); \/* replace callinfo *\/ ci = mrb->c->ci; ci->target_class = MRB_PROC_TARGET_CLASS(m); ci->proc = m; if (MRB_PROC_ENV_P(m)) { mrb_sym mid; struct REnv *e = MRB_PROC_ENV(m); mid = e->mid; if (mid) ci->mid = mid; if (!e->stack) { e->stack = mrb->c->stack; } } \/* prepare stack *\/ if (MRB_PROC_CFUNC_P(m)) { recv = MRB_PROC_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; \/* pop stackpos *\/ ci = mrb->c->ci; mrb->c->stack = ci->stackent; regs[ci->acc] = recv; pc = ci->pc; cipop(mrb); irep = mrb->c->ci->proc->body.irep; pool = irep->pool; syms = irep->syms; JUMP; } else { \/* setup environment for calling method *\/ proc = m; irep = m->body.irep; if (!irep) { mrb->c->stack[0] = mrb_nil_value(); goto L_RETURN; } pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, ci->nregs); if (ci->argc < 0) { if (irep->nregs > 3) { stack_clear(regs+3, irep->nregs-3); } } else if (ci->argc+2 < irep->nregs) { stack_clear(regs+ci->argc+2, irep->nregs-ci->argc-2); } if (MRB_PROC_ENV_P(m)) { regs[0] = MRB_PROC_ENV(m)->stack[0]; } pc = irep->iseq; JUMP; } } CASE(OP_SUPER) { \/* A C R(A) := super(R(A+1),... ,R(A+C+1)) *\/ int a = GETARG_A(i); int n = GETARG_C(i); int argc = (n == CALL_MAXARGS) ? -1 : n; int bidx = (argc < 0) ? a+2 : a+n+1; mrb_method_t m; struct RClass *c; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; mrb_sym mid = ci->mid; struct RClass* target_class = MRB_PROC_TARGET_CLASS(ci->proc); mrb_assert(bidx < ci->nregs); if (mid == 0 || !target_class) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (target_class->tt == MRB_TT_MODULE) { target_class = ci->target_class; if (target_class->tt != MRB_TT_ICLASS) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, \"superclass info lost [mruby limitations]\"); mrb_exc_set(mrb, exc); goto L_RAISE; } } recv = regs[0]; if (!mrb_obj_is_kind_of(mrb, recv, target_class)) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, \"self has wrong type to call super in this context\"); mrb_exc_set(mrb, exc); goto L_RAISE; } blk = regs[bidx]; if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) { blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, \"Proc\", \"to_proc\"); \/* The stack or ci stack might have been reallocated during mrb_convert_type(), see #3622 and #3784 *\/ regs[bidx] = blk; ci = mrb->c->ci; } c = target_class->super; m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_sym missing = mrb_intern_lit(mrb, \"method_missing\"); if (mid != missing) { c = mrb_class(mrb, recv); } m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m)) { mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1); ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } mid = missing; if (argc >= 0) { if (a+2 >= ci->nregs) { stack_extend(mrb, a+3); } regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1); regs[a+2] = blk; argc = -1; } mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(ci->mid)); } \/* push callinfo *\/ ci = cipush(mrb); ci->mid = mid; ci->stackent = mrb->c->stack; ci->target_class = c; ci->pc = pc + 1; ci->argc = argc; \/* prepare stack *\/ mrb->c->stack += a; mrb->c->stack[0] = recv; if (MRB_METHOD_CFUNC_P(m)) { mrb_value v; ci->nregs = (argc < 0) ? 3 : n+2; if (MRB_METHOD_PROC_P(m)) { ci->proc = MRB_METHOD_PROC(m); } v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (!ci->target_class) { \/* return from context modifying method (resume\/yield) *\/ if (ci->acc == CI_ACC_RESUMED) { mrb->jmp = prev_jmp; return v; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->stack[0] = v; \/* pop stackpos *\/ mrb->c->stack = ci->stackent; pc = ci->pc; cipop(mrb); JUMP; } else { \/* fill callinfo *\/ ci->acc = a; \/* setup environment for calling method *\/ proc = ci->proc = MRB_METHOD_PROC(m); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs); pc = irep->iseq; JUMP; } } CASE(OP_ARGARY) { \/* A Bx R(A) := argument array (16=6:1:5:4) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); int m1 = (bx>>10)&0x3f; int r = (bx>>9)&0x1; int m2 = (bx>>4)&0x1f; int lv = (bx>>0)&0xf; mrb_value *stack; if (mrb->c->ci->mid == 0 || mrb->c->ci->target_class == NULL) { mrb_value exc; L_NOSUPER: exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e) goto L_NOSUPER; if (MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) goto L_NOSUPER; stack = e->stack + 1; } if (r == 0) { regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack); } else { mrb_value *pp = NULL; struct RArray *rest; int len = 0; if (mrb_array_p(stack[m1])) { struct RArray *ary = mrb_ary_ptr(stack[m1]); pp = ARY_PTR(ary); len = (int)ARY_LEN(ary); } regs[a] = mrb_ary_new_capa(mrb, m1+len+m2); rest = mrb_ary_ptr(regs[a]); if (m1 > 0) { stack_copy(ARY_PTR(rest), stack, m1); } if (len > 0) { stack_copy(ARY_PTR(rest)+m1, pp, len); } if (m2 > 0) { stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2); } ARY_SET_LEN(rest, m1+len+m2); } regs[a+1] = stack[m1+r+m2]; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ENTER) { \/* Ax arg setup according to flags (23=5:5:1:5:5:1:1) *\/ \/* number of optional arguments times OP_JMP should follow *\/ mrb_aspec ax = GETARG_Ax(i); int m1 = MRB_ASPEC_REQ(ax); int o = MRB_ASPEC_OPT(ax); int r = MRB_ASPEC_REST(ax); int m2 = MRB_ASPEC_POST(ax); \/* unused int k = MRB_ASPEC_KEY(ax); int kd = MRB_ASPEC_KDICT(ax); int b = MRB_ASPEC_BLOCK(ax); *\/ int argc = mrb->c->ci->argc; mrb_value *argv = regs+1; mrb_value *argv0 = argv; int len = m1 + o + r + m2; mrb_value *blk = &argv[argc < 0 ? 1 : argc]; if (argc < 0) { struct RArray *ary = mrb_ary_ptr(regs[1]); argv = ARY_PTR(ary); argc = (int)ARY_LEN(ary); mrb_gc_protect(mrb, regs[1]); } if (mrb->c->ci->proc && MRB_PROC_STRICT_P(mrb->c->ci->proc)) { if (argc >= 0) { if (argc < m1 + m2 || (r == 0 && argc > len)) { argnum_error(mrb, m1+m2); goto L_RAISE; } } } else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) { mrb_gc_protect(mrb, argv[0]); argc = (int)RARRAY_LEN(argv[0]); argv = RARRAY_PTR(argv[0]); } if (argc < len) { int mlen = m2; if (argc < m1+m2) { if (m1 < argc) mlen = argc - m1; else mlen = 0; } regs[len+1] = *blk; \/* move block *\/ SET_NIL_VALUE(regs[argc+1]); if (argv0 != argv) { value_move(®s[1], argv, argc-mlen); \/* m1 + o *\/ } if (argc < m1) { stack_clear(®s[argc+1], m1-argc); } if (mlen) { value_move(®s[len-m2+1], &argv[argc-mlen], mlen); } if (mlen < m2) { stack_clear(®s[len-m2+mlen+1], m2-mlen); } if (r) { regs[m1+o+1] = mrb_ary_new_capa(mrb, 0); } if (o == 0 || argc < m1+m2) pc++; else pc += argc - m1 - m2 + 1; } else { int rnum = 0; if (argv0 != argv) { regs[len+1] = *blk; \/* move block *\/ value_move(®s[1], argv, m1+o); } if (r) { rnum = argc-m1-o-m2; regs[m1+o+1] = mrb_ary_new_from_values(mrb, rnum, argv+m1+o); } if (m2) { if (argc-m2 > m1) { value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2); } } if (argv0 == argv) { regs[len+1] = *blk; \/* move block *\/ } pc += o + 1; } mrb->c->ci->argc = len; \/* clear local (but non-argument) variables *\/ if (irep->nlocals-len-2 > 0) { stack_clear(®s[len+2], irep->nlocals-len-2); } JUMP; } CASE(OP_KARG) { \/* A B C R(A) := kdict[Syms(B)]; if C kdict.rm(Syms(B)) *\/ \/* if C == 2; raise unless kdict.empty? *\/ \/* OP_JMP should follow to skip init code *\/ NEXT; } CASE(OP_KDICT) { \/* A C R(A) := kdict *\/ NEXT; } L_RETURN: i = MKOP_AB(OP_RETURN, GETARG_A(i), OP_R_NORMAL); \/* fall through *\/ CASE(OP_RETURN) { \/* A B return R(A) (B=normal,in-block return\/break) *\/ mrb_callinfo *ci; #define ecall_adjust() do {\\ ptrdiff_t cioff = ci - mrb->c->cibase;\\ ecall(mrb);\\ ci = mrb->c->cibase + cioff;\\ } while (0) ci = mrb->c->ci; if (ci->mid) { mrb_value blk; if (ci->argc < 0) { blk = regs[2]; } else { blk = regs[ci->argc+1]; } if (mrb_type(blk) == MRB_TT_PROC) { struct RProc *p = mrb_proc_ptr(blk); if (!MRB_PROC_STRICT_P(p) && ci > mrb->c->cibase && MRB_PROC_ENV(p) == ci[-1].env) { p->flags |= MRB_PROC_ORPHAN; } } } if (mrb->exc) { mrb_callinfo *ci0; L_RAISE: ci0 = ci = mrb->c->ci; if (ci == mrb->c->cibase) { if (ci->ridx == 0) goto L_FTOP; goto L_RESCUE; } while (ci[0].ridx == ci[-1].ridx) { cipop(mrb); mrb->c->stack = ci->stackent; if (ci->acc == CI_ACC_SKIP && prev_jmp) { mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } ci = mrb->c->ci; if (ci == mrb->c->cibase) { if (ci->ridx == 0) { L_FTOP: \/* fiber top *\/ if (mrb->c == mrb->root_c) { mrb->c->stack = mrb->c->stbase; goto L_STOP; } else { struct mrb_context *c = mrb->c; while (c->eidx > ci->epos) { ecall_adjust(); } if (c->fib) { mrb_write_barrier(mrb, (struct RBasic*)c->fib); } mrb->c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; goto L_RAISE; } } break; } \/* call ensure only when we skip this callinfo *\/ if (ci[0].ridx == ci[-1].ridx) { while (mrb->c->eidx > ci->epos) { ecall_adjust(); } } } L_RESCUE: if (ci->ridx == 0) goto L_STOP; proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; if (ci < ci0) { mrb->c->stack = ci[1].stackent; } stack_extend(mrb, irep->nregs); pc = mrb->c->rescue[--ci->ridx]; } else { int acc; mrb_value v; struct RProc *dst; ci = mrb->c->ci; v = regs[GETARG_A(i)]; mrb_gc_protect(mrb, v); switch (GETARG_B(i)) { case OP_R_RETURN: \/* Fall through to OP_R_NORMAL otherwise *\/ if (ci->acc >=0 && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) { mrb_callinfo *cibase = mrb->c->cibase; dst = top_proc(mrb, proc); if (MRB_PROC_ENV_P(dst)) { struct REnv *e = MRB_PROC_ENV(dst); if (!MRB_ENV_STACK_SHARED_P(e) || e->cxt != mrb->c) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } } while (cibase <= ci && ci->proc != dst) { if (ci->acc < 0) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci--; } if (ci <= cibase) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } break; } case OP_R_NORMAL: NORMAL_RETURN: if (ci == mrb->c->cibase) { struct mrb_context *c; if (!mrb->c->prev) { \/* toplevel return *\/ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } if (mrb->c->prev->ci == mrb->c->prev->cibase) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_FIBER_ERROR, \"double resume\"); mrb_exc_set(mrb, exc); goto L_RAISE; } while (mrb->c->eidx > 0) { ecall(mrb); } \/* automatic yield at the end *\/ c = mrb->c; c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; mrb->c->status = MRB_FIBER_RUNNING; ci = mrb->c->ci; } break; case OP_R_BREAK: if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN; if (MRB_PROC_ORPHAN_P(proc)) { mrb_value exc; L_BREAK_ERROR: exc = mrb_exc_new_str_lit(mrb, E_LOCALJUMP_ERROR, \"break from proc-closure\"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_STACK_SHARED_P(MRB_PROC_ENV(proc))) { goto L_BREAK_ERROR; } else { struct REnv *e = MRB_PROC_ENV(proc); if (e == mrb->c->cibase->env && proc != mrb->c->cibase->proc) { goto L_BREAK_ERROR; } if (e->cxt != mrb->c) { goto L_BREAK_ERROR; } } while (mrb->c->eidx > mrb->c->ci->epos) { ecall_adjust(); } \/* break from fiber block *\/ if (ci == mrb->c->cibase && ci->pc) { struct mrb_context *c = mrb->c; mrb->c = c->prev; c->prev = NULL; ci = mrb->c->ci; } if (ci->acc < 0) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->exc = (struct RObject*)break_new(mrb, proc, v); mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } if (FALSE) { L_BREAK: v = ((struct RBreak*)mrb->exc)->val; proc = ((struct RBreak*)mrb->exc)->proc; mrb->exc = NULL; ci = mrb->c->ci; } mrb->c->stack = ci->stackent; proc = proc->upper; while (mrb->c->cibase < ci && ci[-1].proc != proc) { if (ci[-1].acc == CI_ACC_SKIP) { while (ci < mrb->c->ci) { cipop(mrb); } goto L_BREAK_ERROR; } ci--; } if (ci == mrb->c->cibase) { goto L_BREAK_ERROR; } break; default: \/* cannot happen *\/ break; } while (ci < mrb->c->ci) { cipop(mrb); } ci[0].ridx = ci[-1].ridx; while (mrb->c->eidx > ci->epos) { ecall_adjust(); } if (mrb->c->vmexec && !ci->target_class) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } acc = ci->acc; mrb->c->stack = ci->stackent; cipop(mrb); if (acc == CI_ACC_SKIP || acc == CI_ACC_DIRECT) { mrb_gc_arena_restore(mrb, ai); mrb->jmp = prev_jmp; return v; } pc = ci->pc; ci = mrb->c->ci; DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym2name(mrb, ci->mid))); proc = mrb->c->ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; regs[acc] = v; mrb_gc_arena_restore(mrb, ai); } JUMP; } CASE(OP_TAILCALL) { \/* A B C return call(R(A),Syms(B),R(A+1),... ,R(A+C+1)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int n = GETARG_C(i); mrb_method_t m; struct RClass *c; mrb_callinfo *ci; mrb_value recv; mrb_sym mid = syms[b]; recv = regs[a]; c = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_value sym = mrb_symbol_value(mid); mrb_sym missing = mrb_intern_lit(mrb, \"method_missing\"); m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m)) { mrb_value args; if (n == CALL_MAXARGS) { args = regs[a+1]; } else { args = mrb_ary_new_from_values(mrb, n, regs+a+1); } ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } mid = missing; if (n == CALL_MAXARGS) { mrb_ary_unshift(mrb, regs[a+1], sym); } else { value_move(regs+a+2, regs+a+1, ++n); regs[a+1] = sym; } } \/* replace callinfo *\/ ci = mrb->c->ci; ci->mid = mid; ci->target_class = c; if (n == CALL_MAXARGS) { ci->argc = -1; } else { ci->argc = n; } \/* move stack *\/ value_move(mrb->c->stack, ®s[a], ci->argc+1); if (MRB_METHOD_CFUNC_P(m)) { mrb_value v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb->c->stack[0] = v; mrb_gc_arena_restore(mrb, ai); goto L_RETURN; } else { \/* setup environment for calling method *\/ struct RProc *p = MRB_METHOD_PROC(m); irep = p->body.irep; pool = irep->pool; syms = irep->syms; if (ci->argc < 0) { stack_extend(mrb, (irep->nregs < 3) ? 3 : irep->nregs); } else { stack_extend(mrb, irep->nregs); } pc = irep->iseq; } JUMP; } CASE(OP_BLKPUSH) { \/* A Bx R(A) := block (16=6:1:5:4) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); int m1 = (bx>>10)&0x3f; int r = (bx>>9)&0x1; int m2 = (bx>>4)&0x1f; int lv = (bx>>0)&0xf; mrb_value *stack; if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e || (!MRB_ENV_STACK_SHARED_P(e) && e->mid == 0) || MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } stack = e->stack + 1; } if (mrb_nil_p(stack[m1+r+m2])) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } regs[a] = stack[m1+r+m2]; NEXT; } #define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff)) #define OP_MATH_BODY(op,v1,v2) do {\\ v1(regs[a]) = v1(regs[a]) op v2(regs[a+1]);\\ } while(0) CASE(OP_ADD) { \/* A B C R(A) := R(A)+R(A+1) (Syms[B]=:+,C=1)*\/ int a = GETARG_A(i); \/* need to check if op is overridden *\/ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; mrb_value *regs_a = regs + a; x = mrb_fixnum(regs_a[0]); y = mrb_fixnum(regs_a[1]); if (mrb_int_add_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x + (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x + y); } #else OP_MATH_BODY(+,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x + y); } #else OP_MATH_BODY(+,mrb_float,mrb_float); #endif break; #endif case TYPES2(MRB_TT_STRING,MRB_TT_STRING): regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); break; default: goto L_SEND; } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_SUB) { \/* A B C R(A) := R(A)-R(A+1) (Syms[B]=:-,C=1)*\/ int a = GETARG_A(i); \/* need to check if op is overridden *\/ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; x = mrb_fixnum(regs[a]); y = mrb_fixnum(regs[a+1]); if (mrb_int_sub_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x - y); } #else OP_MATH_BODY(-,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x - y); } #else OP_MATH_BODY(-,mrb_float,mrb_float); #endif break; #endif default: goto L_SEND; } NEXT; } CASE(OP_MUL) { \/* A B C R(A) := R(A)*R(A+1) (Syms[B]=:*,C=1)*\/ int a = GETARG_A(i); \/* need to check if op is overridden *\/ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; x = mrb_fixnum(regs[a]); y = mrb_fixnum(regs[a+1]); if (mrb_int_mul_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x * y); } #else OP_MATH_BODY(*,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x * y); } #else OP_MATH_BODY(*,mrb_float,mrb_float); #endif break; #endif default: goto L_SEND; } NEXT; } CASE(OP_DIV) { \/* A B C R(A) := R(A)\/R(A+1) (Syms[B]=:\/,C=1)*\/ int a = GETARG_A(i); #ifndef MRB_WITHOUT_FLOAT double x, y, f; #endif \/* need to check if op is overridden *\/ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): #ifdef MRB_WITHOUT_FLOAT { mrb_int x = mrb_fixnum(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_INT_VALUE(regs[a], y ? x \/ y : 0); } break; #else x = (mrb_float)mrb_fixnum(regs[a]); y = (mrb_float)mrb_fixnum(regs[a+1]); break; case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): x = (mrb_float)mrb_fixnum(regs[a]); y = mrb_float(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): x = mrb_float(regs[a]); y = (mrb_float)mrb_fixnum(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): x = mrb_float(regs[a]); y = mrb_float(regs[a+1]); break; #endif default: goto L_SEND; } #ifndef MRB_WITHOUT_FLOAT if (y == 0) { if (x > 0) f = INFINITY; else if (x < 0) f = -INFINITY; else \/* if (x == 0) *\/ f = NAN; } else { f = x \/ y; } SET_FLOAT_VALUE(mrb, regs[a], f); #endif NEXT; } CASE(OP_ADDI) { \/* A B C R(A) := R(A)+C (Syms[B]=:+)*\/ int a = GETARG_A(i); \/* need to check if + is overridden *\/ switch (mrb_type(regs[a])) { case MRB_TT_FIXNUM: { mrb_int x = mrb_fixnum(regs[a]); mrb_int y = GETARG_C(i); mrb_int z; if (mrb_int_add_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case MRB_TT_FLOAT: #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); SET_FLOAT_VALUE(mrb, regs[a], x + GETARG_C(i)); } #else mrb_float(regs[a]) += GETARG_C(i); #endif break; #endif default: SET_INT_VALUE(regs[a+1], GETARG_C(i)); i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1); goto L_SEND; } NEXT; } CASE(OP_SUBI) { \/* A B C R(A) := R(A)-C (Syms[B]=:-)*\/ int a = GETARG_A(i); mrb_value *regs_a = regs + a; \/* need to check if + is overridden *\/ switch (mrb_type(regs_a[0])) { case MRB_TT_FIXNUM: { mrb_int x = mrb_fixnum(regs_a[0]); mrb_int y = GETARG_C(i); mrb_int z; if (mrb_int_sub_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x - (mrb_float)y); break; #endif } SET_INT_VALUE(regs_a[0], z); } break; #ifndef MRB_WITHOUT_FLOAT case MRB_TT_FLOAT: #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); SET_FLOAT_VALUE(mrb, regs[a], x - GETARG_C(i)); } #else mrb_float(regs_a[0]) -= GETARG_C(i); #endif break; #endif default: SET_INT_VALUE(regs_a[1], GETARG_C(i)); i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1); goto L_SEND; } NEXT; } #define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1])) #ifdef MRB_WITHOUT_FLOAT #define OP_CMP(op) do {\\ int result;\\ \/* need to check if - is overridden *\/\\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\ break;\\ default:\\ goto L_SEND;\\ }\\ if (result) {\\ SET_TRUE_VALUE(regs[a]);\\ }\\ else {\\ SET_FALSE_VALUE(regs[a]);\\ }\\ } while(0) #else #define OP_CMP(op) do {\\ int result;\\ \/* need to check if - is overridden *\/\\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\ break;\\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\ break;\\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\\ result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\ break;\\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\ result = OP_CMP_BODY(op,mrb_float,mrb_float);\\ break;\\ default:\\ goto L_SEND;\\ }\\ if (result) {\\ SET_TRUE_VALUE(regs[a]);\\ }\\ else {\\ SET_FALSE_VALUE(regs[a]);\\ }\\ } while(0) #endif CASE(OP_EQ) { \/* A B C R(A) := R(A)==R(A+1) (Syms[B]=:==,C=1)*\/ int a = GETARG_A(i); if (mrb_obj_eq(mrb, regs[a], regs[a+1])) { SET_TRUE_VALUE(regs[a]); } else { OP_CMP(==); } NEXT; } CASE(OP_LT) { \/* A B C R(A) := R(A)R(A+1) (Syms[B]=:>,C=1)*\/ int a = GETARG_A(i); OP_CMP(>); NEXT; } CASE(OP_GE) { \/* A B C R(A) := R(A)>=R(A+1) (Syms[B]=:>=,C=1)*\/ int a = GETARG_A(i); OP_CMP(>=); NEXT; } CASE(OP_ARRAY) { \/* A B C R(A) := ary_new(R(B),R(B+1)..R(B+C)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value v = mrb_ary_new_from_values(mrb, c, ®s[b]); regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYCAT) { \/* A B mrb_ary_concat(R(A),R(B)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); mrb_value splat = mrb_ary_splat(mrb, regs[b]); mrb_ary_concat(mrb, regs[a], splat); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYPUSH) { \/* A B R(A).push(R(B)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); mrb_ary_push(mrb, regs[a], regs[b]); NEXT; } CASE(OP_AREF) { \/* A B C R(A) := R(B)[C] *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value v = regs[b]; if (!mrb_array_p(v)) { if (c == 0) { regs[a] = v; } else { SET_NIL_VALUE(regs[a]); } } else { v = mrb_ary_ref(mrb, v, c); regs[a] = v; } NEXT; } CASE(OP_ASET) { \/* A B C R(B)[C] := R(A) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_ary_set(mrb, regs[b], c, regs[a]); NEXT; } CASE(OP_APOST) { \/* A B C *R(A),R(A+1)..R(A+C) := R(A) *\/ int a = GETARG_A(i); mrb_value v = regs[a]; int pre = GETARG_B(i); int post = GETARG_C(i); struct RArray *ary; int len, idx; if (!mrb_array_p(v)) { v = mrb_ary_new_from_values(mrb, 1, ®s[a]); } ary = mrb_ary_ptr(v); len = (int)ARY_LEN(ary); if (len > pre + post) { v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre); regs[a++] = v; while (post--) { regs[a++] = ARY_PTR(ary)[len-post-1]; } } else { v = mrb_ary_new_capa(mrb, 0); regs[a++] = v; for (idx=0; idx+prereps[b]; if (c & OP_L_CAPTURE) { p = mrb_closure_new(mrb, nirep); } else { p = mrb_proc_new(mrb, nirep); p->flags |= MRB_PROC_SCOPE; } if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT; regs[a] = mrb_obj_value(p); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_OCLASS) { \/* A R(A) := ::Object *\/ regs[GETARG_A(i)] = mrb_obj_value(mrb->object_class); NEXT; } CASE(OP_CLASS) { \/* A B R(A) := newclass(R(A),Syms(B),R(A+1)) *\/ struct RClass *c = 0, *baseclass; int a = GETARG_A(i); mrb_value base, super; mrb_sym id = syms[GETARG_B(i)]; base = regs[a]; super = regs[a+1]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); base = mrb_obj_value(baseclass); } c = mrb_vm_define_class(mrb, base, super, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_MODULE) { \/* A B R(A) := newmodule(R(A),Syms(B)) *\/ struct RClass *c = 0, *baseclass; int a = GETARG_A(i); mrb_value base; mrb_sym id = syms[GETARG_B(i)]; base = regs[a]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); base = mrb_obj_value(baseclass); } c = mrb_vm_define_module(mrb, base, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EXEC) { \/* A Bx R(A) := blockexec(R(A),SEQ[Bx]) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_callinfo *ci; mrb_value recv = regs[a]; struct RProc *p; mrb_irep *nirep = irep->reps[bx]; \/* prepare closure *\/ p = mrb_proc_new(mrb, nirep); p->c = NULL; mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc); MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv)); p->flags |= MRB_PROC_SCOPE; \/* prepare call stack *\/ ci = cipush(mrb); ci->pc = pc + 1; ci->acc = a; ci->mid = 0; ci->stackent = mrb->c->stack; ci->argc = 0; ci->target_class = mrb_class_ptr(recv); \/* prepare stack *\/ mrb->c->stack += a; \/* setup block to call *\/ ci->proc = p; irep = p->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, ci->nregs); stack_clear(regs+1, ci->nregs-1); pc = irep->iseq; JUMP; } CASE(OP_METHOD) { \/* A B R(A).newmethod(Syms(B),R(A+1)) *\/ int a = GETARG_A(i); struct RClass *c = mrb_class_ptr(regs[a]); struct RProc *p = mrb_proc_ptr(regs[a+1]); mrb_method_t m; MRB_METHOD_FROM_PROC(m, p); mrb_define_method_raw(mrb, c, syms[GETARG_B(i)], m); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_SCLASS) { \/* A B R(A) := R(B).singleton_class *\/ int a = GETARG_A(i); int b = GETARG_B(i); regs[a] = mrb_singleton_class(mrb, regs[b]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_TCLASS) { \/* A R(A) := target_class *\/ if (!mrb->c->ci->target_class) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, \"no target class or module\"); mrb_exc_set(mrb, exc); goto L_RAISE; } regs[GETARG_A(i)] = mrb_obj_value(mrb->c->ci->target_class); NEXT; } CASE(OP_RANGE) { \/* A B C R(A) := range_new(R(B),R(B+1),C) *\/ int b = GETARG_B(i); mrb_value val = mrb_range_new(mrb, regs[b], regs[b+1], GETARG_C(i)); regs[GETARG_A(i)] = val; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_DEBUG) { \/* A B C debug print R(A),R(B),R(C) *\/ #ifdef MRB_ENABLE_DEBUG_HOOK mrb->debug_op_hook(mrb, irep, pc, regs); #else #ifndef MRB_DISABLE_STDIO printf(\"OP_DEBUG %d %d %d\\n\", GETARG_A(i), GETARG_B(i), GETARG_C(i)); #else abort(); #endif #endif NEXT; } CASE(OP_STOP) { \/* stop VM *\/ L_STOP: while (mrb->c->eidx > 0) { ecall(mrb); } ERR_PC_CLR(mrb); mrb->jmp = prev_jmp; if (mrb->exc) { return mrb_obj_value(mrb->exc); } return regs[irep->nlocals]; } CASE(OP_ERR) { \/* Bx raise RuntimeError with message Lit(Bx) *\/ mrb_value msg = mrb_str_dup(mrb, pool[GETARG_Bx(i)]); mrb_value exc; if (GETARG_A(i) == 0) { exc = mrb_exc_new_str(mrb, E_RUNTIME_ERROR, msg); } else { exc = mrb_exc_new_str(mrb, E_LOCALJUMP_ERROR, msg); } ERR_PC_SET(mrb, pc); mrb_exc_set(mrb, exc); goto L_RAISE; } } END_DISPATCH; #undef regs } MRB_CATCH(&c_jmp) { exc_catched = TRUE; goto RETRY_TRY_BLOCK; } MRB_END_EXC(&c_jmp); }","output":{"is_vulnerable":"True","vulnerability_types":["Integer Overflow or Wraparound"],"explanation":"In versions of mruby up to and including 1.4.0, an integer overflow exists in src\/vm.c::mrb_vm_exec() when handling OP_GETUPVAR in the presence of deep scope nesting, resulting in a use-after-free. An attacker that can cause Ruby code to be run can use this to possibly execute arbitrary code.","severity_level":"NoInfo","cwe":"CWE-190","cve":"CVE-2018-10191"}} -{"idx":518319,"input":"unsigned CjfifDecode::DecodeMarker() { TCHAR acIdentifier[MAX_IDENTIFIER]; CString strTmp; CString strFull; \/\/ Used for concatenation unsigned nLength; \/\/ General purpose unsigned nTmpVal; unsigned nCode; unsigned long nPosEnd; unsigned long nPosSaved; \/\/ General-purpose saved position in file unsigned long nPosExifStart; unsigned nRet; \/\/ General purpose return value bool bRet; unsigned long nPosMarkerStart; \/\/ Offset for current marker unsigned nColTransform = 0; \/\/ Color Transform from APP14 marker \/\/ For DQT CString strDqtPrecision = _T(\"\"); CString strDqtZigZagOrder = _T(\"\"); if (Buf(m_nPos) != 0xFF) { if (m_nPos == 0) { \/\/ Don't give error message if we've already alerted them of AVI \/ PSD if ((!m_bAvi) && (!m_bPsd)) { strTmp.Format(_T(\"NOTE: File did not start with JPEG marker. Consider using [Tools->Img Search Fwd] to locate embedded JPEG.\")); m_pLog->AddLineErr(strTmp); } } else { strTmp.Format(_T(\"ERROR: Expected marker 0xFF, got 0x%02X @ offset 0x%08X. Consider using [Tools->Img Search Fwd\/Rev].\"),Buf(m_nPos),m_nPos); m_pLog->AddLineErr(strTmp); } m_nPos++; return DECMARK_ERR; } m_nPos++; \/\/ Read the current marker code nCode = Buf(m_nPos++); \/\/ Handle Marker Padding \/\/ \/\/ According to Section B.1.1.2: \/\/ \"Any marker may optionally be preceded by any number of fill bytes, which are bytes assigned code XFF.\" \/\/ unsigned nSkipMarkerPad = 0; while (nCode == 0xFF) { \/\/ Count the pad nSkipMarkerPad++; \/\/ Read another byte nCode = Buf(m_nPos++); } \/\/ Report out any padding if (nSkipMarkerPad>0) { strTmp.Format(_T(\"*** Skipped %u marker pad bytes ***\"),nSkipMarkerPad); m_pLog->AddLineHdr(strTmp); } \/\/ Save the current marker offset nPosMarkerStart = m_nPos; AddHeader(nCode); switch (nCode) { case JFIF_SOI: \/\/ SOI m_bStateSoi = true; break; case JFIF_APP12: \/\/ Photoshop DUCKY (Save For Web) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; \/\/ Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T(\"Ducky\")) != 0) { m_pLog->AddLine(_T(\" Not Photoshop DUCKY. Skipping remainder.\")); } else \/\/ Photoshop { \/\/ Please see reference on http:\/\/cpan.uwinnipeg.ca\/htdocs\/Image-ExifTool\/Image\/ExifTool\/APP12.pm.html \/\/ A direct indexed approach should be safe m_nImgQualPhotoshopSfw = Buf(m_nPos+6); strTmp.Format(_T(\" Photoshop Save For Web Quality = [%d]\"),m_nImgQualPhotoshopSfw); m_pLog->AddLine(strTmp); } \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP14: \/\/ JPEG Adobe tag nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; \/\/ Some files had very short segment (eg. nLength=2) if (nLength < 2+12) { m_pLog->AddLine(_T(\" Segment too short for Identifier. Skipping remainder.\")); m_nPos = nPosSaved+nLength; break; } m_nPos += 2; \/\/ Move past length now that we've used it \/\/ TODO: Confirm Adobe flag m_nPos += 5; nTmpVal = Buf(m_nPos+0)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" DCTEncodeVersion = %u\"),nTmpVal); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3); strTmp.Format(_T(\" APP14Flags0 = %u\"),nTmpVal); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos+4)*256 + Buf(m_nPos+5); strTmp.Format(_T(\" APP14Flags1 = %u\"),nTmpVal); m_pLog->AddLine(strTmp); nColTransform = Buf(m_nPos+6); switch (nColTransform) { case APP14_COLXFM_UNK_RGB: strTmp.Format(_T(\" ColorTransform = %u [Unknown (RGB or CMYK)]\"),nColTransform); break; case APP14_COLXFM_YCC: strTmp.Format(_T(\" ColorTransform = %u [YCbCr]\"),nColTransform); break; case APP14_COLXFM_YCCK: strTmp.Format(_T(\" ColorTransform = %u [YCCK]\"),nColTransform); break; default: strTmp.Format(_T(\" ColorTransform = %u [???]\"),nColTransform); break; } m_pLog->AddLine(strTmp); m_nApp14ColTransform = (nColTransform & 0xFF); \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP13: \/\/ Photoshop (Save As) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; \/\/ Some files had very short segment (eg. nLength=2) if (nLength < 2+20) { m_pLog->AddLine(_T(\" Segment too short for Identifier. Skipping remainder.\")); m_nPos = nPosSaved+nLength; break; } m_nPos += 2; \/\/ Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T(\"Photoshop 3.0\")) != 0) { m_pLog->AddLine(_T(\" Not Photoshop. Skipping remainder.\")); } else \/\/ Photoshop { DecodeApp13Ps(); } \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP1: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; \/\/ Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier); if (!_tcsnccmp(acIdentifier,_T(\"http:\/\/ns.adobe.com\/xap\/1.0\/\\x00\"),29) != 0) { \/\/ XMP m_pLog->AddLine(_T(\" XMP = \")); m_nPos++; unsigned nPosMarkerEnd = nPosSaved+nLength-1; unsigned sXmpLen = nPosMarkerEnd-m_nPos; char cXmpChar; bool bNonSpace; CString strLine; \/\/ Reset state strLine = _T(\" |\"); bNonSpace = false; for (unsigned nInd=0;nIndBuf(m_nPos+nInd); \/\/ Detect a non-space in line if ((cXmpChar != 0x20) && (cXmpChar != 0x0A)) { bNonSpace = true; } \/\/ Detect Linefeed, print out line if (cXmpChar == 0x0A) { \/\/ Only print line if some non-space elements! if (bNonSpace) { m_pLog->AddLine(strLine); } \/\/ Reset state strLine = _T(\" |\"); bNonSpace = false; } else { \/\/ Add the char strLine.AppendChar(cXmpChar); } } } else if (!_tcscmp(acIdentifier,_T(\"Exif\")) != 0) { \/\/ Only decode it further if it is EXIF format m_nPos += 2; \/\/ Skip two 00 bytes nPosExifStart = m_nPos; \/\/ Save m_nPos @ start of EXIF used for all IFD offsets \/\/ =========== EXIF TIFF Header (Start) =========== \/\/ - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.5.2 \/\/ - Contents (8 bytes total) \/\/ - Byte order (2 bytes) \/\/ - 0x002A (2 bytes) \/\/ - Offset of 0th IFD (4 bytes) unsigned char acIdentifierTiff[9]; strFull = _T(\"\"); strTmp = _T(\"\"); strFull = _T(\" Identifier TIFF = \"); for (unsigned int i=0;i<8;i++) { acIdentifierTiff[i] = (unsigned char)Buf(m_nPos++); } strTmp = PrintAsHexUC(acIdentifierTiff,8); strFull += strTmp; m_pLog->AddLine(strFull); switch (acIdentifierTiff[0]*256+acIdentifierTiff[1]) { case 0x4949: \/\/ \"II\" \/\/ Intel alignment m_nImgExifEndian = 0; m_pLog->AddLine(_T(\" Endian = Intel (little)\")); break; case 0x4D4D: \/\/ \"MM\" \/\/ Motorola alignment m_nImgExifEndian = 1; m_pLog->AddLine(_T(\" Endian = Motorola (big)\")); break; } \/\/ We expect the TAG mark of 0x002A (depending on endian mode) unsigned test_002a; test_002a = ByteSwap2(acIdentifierTiff[2],acIdentifierTiff[3]); strTmp.Format(_T(\" TAG Mark x002A = 0x%04X\"),test_002a); m_pLog->AddLine(strTmp); unsigned nIfdCount; \/\/ Current IFD # unsigned nOffsetIfd1; \/\/ Mark pointer to EXIF Sub IFD as 0 so that we can \/\/ detect if the tag never showed up. m_nImgExifSubIfdPtr = 0; m_nImgExifMakerPtr = 0; m_nImgExifGpsIfdPtr = 0; m_nImgExifInteropIfdPtr = 0; bool exif_done = FALSE; nOffsetIfd1 = ByteSwap4(acIdentifierTiff[4],acIdentifierTiff[5], acIdentifierTiff[6],acIdentifierTiff[7]); \/\/ =========== EXIF TIFF Header (End) =========== \/\/ =========== EXIF IFD 0 =========== \/\/ Do we start the 0th IFD for the \"Primary Image Data\"? \/\/ Even though the nOffsetIfd1 pointer should indicate to \/\/ us where the IFD should start (0x0008 if immediately after \/\/ EXIF TIFF Header), I have observed JPEG files that \/\/ do not contain the IFD. Therefore, we must check for this \/\/ condition by comparing against the APP marker length. \/\/ Example file: http:\/\/img9.imageshack.us\/img9\/194\/90114543.jpg if ((nPosSaved + nLength) <= (nPosExifStart+nOffsetIfd1)) { \/\/ We've run out of space for any IFD, so cancel now exif_done = true; m_pLog->AddLine(_T(\" NOTE: No IFD entries\")); } nIfdCount = 0; while (!exif_done) { m_pLog->AddLine(_T(\"\")); strTmp.Format(_T(\"IFD%u\"),nIfdCount); \/\/ Process the IFD nRet = DecodeExifIfd(strTmp,nPosExifStart,nOffsetIfd1); \/\/ Now that we have gone through all entries in the IFD directory, \/\/ we read the offset to the next IFD nOffsetIfd1 = ByteSwap4(Buf(m_nPos+0),Buf(m_nPos+1),Buf(m_nPos+2),Buf(m_nPos+3)); m_nPos += 4; strTmp.Format(_T(\" Offset to Next IFD = 0x%08X\"),nOffsetIfd1); m_pLog->AddLine(strTmp); if (nRet != 0) { \/\/ Error condition (DecodeExifIfd returned error) nOffsetIfd1 = 0x00000000; } if (nOffsetIfd1 == 0x00000000) { \/\/ Either error condition or truly end of IFDs exif_done = TRUE; } else { nIfdCount++; } } \/\/ while ! exif_done \/\/ If EXIF SubIFD was defined, then handle it now if (m_nImgExifSubIfdPtr != 0) { m_pLog->AddLine(_T(\"\")); DecodeExifIfd(_T(\"SubIFD\"),nPosExifStart,m_nImgExifSubIfdPtr); } if (m_nImgExifMakerPtr != 0) { m_pLog->AddLine(_T(\"\")); DecodeExifIfd(_T(\"MakerIFD\"),nPosExifStart,m_nImgExifMakerPtr); } if (m_nImgExifGpsIfdPtr != 0) { m_pLog->AddLine(_T(\"\")); DecodeExifIfd(_T(\"GPSIFD\"),nPosExifStart,m_nImgExifGpsIfdPtr); } if (m_nImgExifInteropIfdPtr != 0) { m_pLog->AddLine(_T(\"\")); DecodeExifIfd(_T(\"InteropIFD\"),nPosExifStart,m_nImgExifInteropIfdPtr); } } else { strTmp.Format(_T(\"Identifier [%s] not supported. Skipping remainder.\"),(LPCTSTR)acIdentifier); m_pLog->AddLine(strTmp); } \/\/\/\/\/\/\/\/\/\/ \/\/ Dump out Makernote area \/\/ TODO: Disabled for now #if 0 unsigned ptr_base; if (m_bVerbose) { if (m_nImgExifMakerPtr != 0) { \/\/ FIXME: Seems that nPosExifStart is not initialized in VERBOSE mode ptr_base = nPosExifStart+m_nImgExifMakerPtr; m_pLog->AddLine(_T(\"Exif Maker IFD DUMP\")); strFull.Format(_T(\" MarkerOffset @ 0x%08X\"),ptr_base); m_pLog->AddLine(strFull); } } #endif \/\/ End of dump out makernote area \/\/ Restore file position m_nPos = nPosSaved; \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP2: \/\/ Typically used for Flashpix and possibly ICC profiles \/\/ Photoshop (Save As) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; \/\/ Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T(\"FPXR\")) == 0) { \/\/ Photoshop m_pLog->AddLine(_T(\" FlashPix:\")); DecodeApp2Flashpix(); } else if (_tcscmp(acIdentifier,_T(\"ICC_PROFILE\")) == 0) { \/\/ ICC Profile m_pLog->AddLine(_T(\" ICC Profile:\")); DecodeApp2IccProfile(nLength); } else { m_pLog->AddLine(_T(\" Not supported. Skipping remainder.\")); } \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP3: case JFIF_APP4: case JFIF_APP5: case JFIF_APP6: case JFIF_APP7: case JFIF_APP8: case JFIF_APP9: case JFIF_APP10: case JFIF_APP11: \/\/case JFIF_APP12: \/\/ Handled separately \/\/case JFIF_APP13: \/\/ Handled separately \/\/case JFIF_APP14: \/\/ Handled separately case JFIF_APP15: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); if (m_bVerbose) { strFull = _T(\"\"); for (unsigned int i=0;iAddLine(strFull); strFull = _T(\"\"); } } m_pLog->AddLine(strFull); strFull = _T(\"\"); for (unsigned int i=0;iAddLine(strFull); } } m_pLog->AddLine(strFull); } \/\/ nVerbose m_nPos += nLength; break; case JFIF_APP0: \/\/ APP0 nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); _tcscpy_s(m_acApp0Identifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); m_acApp0Identifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),m_acApp0Identifier); m_pLog->AddLine(strTmp); if (!_tcscmp(m_acApp0Identifier,_T(\"JFIF\"))) { \/\/ Only process remainder if it is JFIF. This marker \/\/ is also used for application-specific functions. m_nPos += (unsigned)(_tcslen(m_acApp0Identifier)+1); m_nImgVersionMajor = Buf(m_nPos++); m_nImgVersionMinor = Buf(m_nPos++); strTmp.Format(_T(\" version = [%u.%u]\"),m_nImgVersionMajor,m_nImgVersionMinor); m_pLog->AddLine(strTmp); m_nImgUnits = Buf(m_nPos++); m_nImgDensityX = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/m_nImgDensityX = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; m_nImgDensityY = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/m_nImgDensityY = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; strTmp.Format(_T(\" density = %u x %u \"),m_nImgDensityX,m_nImgDensityY); strFull = strTmp; switch (m_nImgUnits) { case 0: strFull += _T(\"(aspect ratio)\"); m_pLog->AddLine(strFull); break; case 1: strFull += _T(\"DPI (dots per inch)\"); m_pLog->AddLine(strFull); break; case 2: strFull += _T(\"DPcm (dots per cm)\"); m_pLog->AddLine(strFull); break; default: strTmp.Format(_T(\"ERROR: Unknown ImgUnits parameter [%u]\"),m_nImgUnits); strFull += strTmp; m_pLog->AddLineWarn(strFull); \/\/return DECMARK_ERR; break; } m_nImgThumbSizeX = Buf(m_nPos++); m_nImgThumbSizeY = Buf(m_nPos++); strTmp.Format(_T(\" thumbnail = %u x %u\"),m_nImgThumbSizeX,m_nImgThumbSizeY); m_pLog->AddLine(strTmp); \/\/ Unpack the thumbnail: unsigned thumbnail_r,thumbnail_g,thumbnail_b; if (m_nImgThumbSizeX && m_nImgThumbSizeY) { for (unsigned y=0;yAddLine(strFull); } } } \/\/ TODO: \/\/ - In JPEG-B mode (GeoRaster), we will need to fake out \/\/ the DHT & DQT tables here. Unfortunately, we'll have to \/\/ rely on the user to put us into this mode as there is nothing \/\/ in the file that specifies this mode. \/* \/\/ TODO: Need to ensure that Faked DHT is correct table AddHeader(JFIF_DHT_FAKE); DecodeDHT(true); \/\/ Need to mark DHT tables as OK m_bStateDht = true; m_bStateDhtFake = true; m_bStateDhtOk = true; \/\/ ... same for DQT *\/ } else if (!_tcsnccmp(m_acApp0Identifier,_T(\"AVI1\"),4)) { \/\/ AVI MJPEG type \/\/ Need to fill in predefined DHT table from spec: \/\/ OpenDML file format for AVI, section \"Proposed Data Chunk Format\" \/\/ Described in MMREG.H m_pLog->AddLine(_T(\" Detected MotionJPEG\")); m_pLog->AddLine(_T(\" Importing standard Huffman table...\")); m_pLog->AddLine(_T(\"\")); AddHeader(JFIF_DHT_FAKE); DecodeDHT(true); \/\/ Need to mark DHT tables as OK m_bStateDht = true; m_bStateDhtFake = true; m_bStateDhtOk = true; m_nPos += nLength-2; \/\/ Skip over, and undo length short read } else { \/\/ Not JFIF or AVI1 m_pLog->AddLine(_T(\" Not known APP0 type. Skipping remainder.\")); m_nPos += nLength-2; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DQT: \/\/ Define quantization tables m_bStateDqt = true; unsigned nDqtPrecision_Pq; unsigned nDqtQuantDestId_Tq; nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Lq nPosEnd = m_nPos+nLength; m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Table length = %u\"),nLength); strTmp.Format(_T(\" Table length = %u\"),nLength); m_pLog->AddLine(strTmp); while (nPosEnd > m_nPos) { strTmp.Format(_T(\" ----\")); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos++); \/\/ Pq | Tq nDqtPrecision_Pq = (nTmpVal & 0xF0) >> 4; \/\/ Pq, range 0-1 nDqtQuantDestId_Tq = nTmpVal & 0x0F; \/\/ Tq, range 0-3 \/\/ Decode per ITU-T.81 standard #if 1 if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T(\"8 bits\"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T(\"16 bits\"); } else { strTmp.Format(_T(\" Unsupported precision value [%u]\"),nDqtPrecision_Pq); m_pLog->AddLineWarn(strTmp); strDqtPrecision = _T(\"???\"); \/\/ FIXME: Consider terminating marker parsing early } if (!ValidateValue(nDqtPrecision_Pq,0,1,_T(\"DQT Precision \"),true,0)) return DECMARK_ERR; if (!ValidateValue(nDqtQuantDestId_Tq,0,3,_T(\"DQT Destination ID \"),true,0)) return DECMARK_ERR; strTmp.Format(_T(\" Precision=%s\"),(LPCTSTR)strDqtPrecision); m_pLog->AddLine(strTmp); #else \/\/ Decode with additional DQT extension (ITU-T-JPEG-Plus-Proposal_R3.doc) if ((nDqtPrecision_Pq & 0xE) == 0) { \/\/ Per ITU-T.81 Standard if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T(\"8 bits\"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T(\"16 bits\"); } strTmp.Format(_T(\" Precision=%s\"),strDqtPrecision); m_pLog->AddLine(strTmp); } else { \/\/ Non-standard \/\/ JPEG-Plus-Proposal-R3: \/\/ - Alternative sub-block-wise sequence strTmp.Format(_T(\" Non-Standard DQT Extension detected\")); m_pLog->AddLineWarn(strTmp); \/\/ FIXME: Should prevent attempt to decode until this is implemented if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T(\"8 bits\"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T(\"16 bits\"); } strTmp.Format(_T(\" Precision=%s\"),strDqtPrecision); m_pLog->AddLine(strTmp); if ((nDqtPrecision_Pq & 0x2) == 0) { strDqtZigZagOrder = _T(\"Diagonal zig-zag coeff scan seqeunce\"); } else if ((nDqtPrecision_Pq & 0x2) == 1) { strDqtZigZagOrder = _T(\"Alternate coeff scan seqeunce\"); } strTmp.Format(_T(\" Coeff Scan Sequence=%s\"),strDqtZigZagOrder); m_pLog->AddLine(strTmp); if ((nDqtPrecision_Pq & 0x4) == 1) { strTmp.Format(_T(\" Custom coeff scan sequence\")); m_pLog->AddLine(strTmp); \/\/ Now expect sequence of 64 coefficient entries CString strSequence = _T(\"\"); for (unsigned nInd=0;nInd<64;nInd++) { nTmpVal = Buf(m_nPos++); strTmp.Format(_T(\"%u\"),nTmpVal); strSequence += strTmp; if (nInd!=63) { strSequence += _T(\", \"); } } strTmp.Format(_T(\" Custom sequence = [ %s ]\"),strSequence); m_pLog->AddLine(strTmp); } } #endif strTmp.Format(_T(\" Destination ID=%u\"),nDqtQuantDestId_Tq); if (nDqtQuantDestId_Tq == 0) { strTmp += _T(\" (Luminance)\"); } else if (nDqtQuantDestId_Tq == 1) { strTmp += _T(\" (Chrominance)\"); } else if (nDqtQuantDestId_Tq == 2) { strTmp += _T(\" (Chrominance)\"); } else { strTmp += _T(\" (???)\"); } m_pLog->AddLine(strTmp); \/\/ FIXME: The following is somewhat superseded by ValidateValue() above \/\/ with the exception of skipping remainder if (nDqtQuantDestId_Tq >= MAX_DQT_DEST_ID) { strTmp.Format(_T(\"ERROR: Destination ID = %u, >= %u\"),nDqtQuantDestId_Tq,MAX_DQT_DEST_ID); m_pLog->AddLineErr(strTmp); if (!m_pAppConfig->bRelaxedParsing) { m_pLog->AddLineErr(_T(\" Stopping decode\")); return DECMARK_ERR; } else { \/\/ Now skip remainder of DQT \/\/ FIXME strTmp.Format(_T(\" Skipping remainder of marker [%u bytes]\"),nPosMarkerStart + nLength - m_nPos); m_pLog->AddLineWarn(strTmp); m_pLog->AddLine(_T(\"\")); m_nPos = nPosMarkerStart + nLength; return DECMARK_OK; } } bool bQuantAllOnes = true; double dComparePercent; double dSumPercent=0; double dSumPercentSqr=0; for (unsigned nCoeffInd=0;nCoeffInd low freq \/\/ To X,Y, left-to-right, top-to-bottom \/\/ Flag this DQT table as being set! m_abImgDqtSet[nDqtQuantDestId_Tq] = true; unsigned nCoeffInd; \/\/ Now display the table for (unsigned nDqtY=0;nDqtY<8;nDqtY++) { strFull.Format(_T(\" DQT, Row #%u: \"),nDqtY); for (unsigned nDqtX=0;nDqtX<8;nDqtX++) { nCoeffInd = nDqtY*8+nDqtX; strTmp.Format(_T(\"%3u \"),m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]); strFull += strTmp; \/\/ Store the DQT entry into the Image Decoder bRet = m_pImgDec->SetDqtEntry(nDqtQuantDestId_Tq,nCoeffInd,glb_anUnZigZag[nCoeffInd], m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]); DecodeErrCheck(bRet); } \/\/ Now add the compare with Annex K \/\/ Decided to disable this as it was confusing users \/* strFull += _T(\" AnnexRatio: <\"); for (unsigned nDqtX=0;nDqtX<8;nDqtX++) { nCoeffInd = nDqtY*8+nDqtX; if (nDqtQuantDestId_Tq == 0) { strTmp.Format(_T(\"%5.1f \"),m_afStdQuantLumCompare[nCoeffInd]); } else { strTmp.Format(_T(\"%5.1f \"),m_afStdQuantChrCompare[nCoeffInd]); } strFull += strTmp; } strFull += _T(\">\"); *\/ m_pLog->AddLine(strFull); } \/\/ Perform some statistical analysis of the quality factor \/\/ to determine the likelihood of the current quantization \/\/ table being a scaled version of the \"standard\" tables. \/\/ If the variance is high, it is unlikely to be the case. double dQuality; double dVariance; dSumPercent \/= 64.0; \/* mean scale factor *\/ dSumPercentSqr \/= 64.0; dVariance = dSumPercentSqr - (dSumPercent * dSumPercent); \/* variance *\/ \/\/ Generate the equivalent IJQ \"quality\" factor if (bQuantAllOnes) \/* special case for all-ones table *\/ dQuality = 100.0; else if (dSumPercent <= 100.0) dQuality = (200.0 - dSumPercent) \/ 2.0; else dQuality = 5000.0 \/ dSumPercent; \/\/ Save the quality rating for later m_adImgDqtQual[nDqtQuantDestId_Tq] = dQuality; strTmp.Format(_T(\" Approx quality factor = %.2f (scaling=%.2f variance=%.2f)\"), dQuality,dSumPercent,dVariance); m_pLog->AddLine(strTmp); } m_bStateDqtOk = true; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DAC: \/\/ DAC (Arithmetic Coding) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ La m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Arithmetic coding header length = %u\"),nLength); strTmp.Format(_T(\" Arithmetic coding header length = %u\"),nLength); m_pLog->AddLine(strTmp); unsigned nDAC_n; unsigned nDAC_Tc,nDAC_Tb; unsigned nDAC_Cs; nDAC_n = (nLength>2)?(nLength-2)\/2:0; for (unsigned nInd=0;nInd> 4; nDAC_Tb = (nTmpVal & 0x0F); \/\/XXX strTmp.Format(_T(\" #%02u: Table class = %u\"),nInd+1,nDAC_Tc); strTmp.Format(_T(\" #%02u: Table class = %u\"),nInd+1,nDAC_Tc); m_pLog->AddLine(strTmp); \/\/XXX strTmp.Format(_T(\" #%02u: Table destination identifier = %u\"),nInd+1,nDAC_Tb); strTmp.Format(_T(\" #%02u: Table destination identifier = %u\"),nInd+1,nDAC_Tb); m_pLog->AddLine(strTmp); nDAC_Cs = Buf(m_nPos++); \/\/ Cs \/\/XXX strTmp.Format(_T(\" #%02u: Conditioning table value = %u\"),nInd+1,nDAC_Cs); strTmp.Format(_T(\" #%02u: Conditioning table value = %u\"),nInd+1,nDAC_Cs); m_pLog->AddLine(strTmp); if (!ValidateValue(nDAC_Tc,0,1,_T(\"Table class \"),true,0)) return DECMARK_ERR; if (!ValidateValue(nDAC_Tb,0,3,_T(\"Table destination ID \"),true,0)) return DECMARK_ERR; \/\/ Parameter range constraints per Table B.6: \/\/ ------------|-------------------------|-------------------|------------ \/\/ | Sequential DCT | Progressive DCT | Lossless \/\/ Parameter | Baseline Extended | | \/\/ ------------|-----------|-------------|-------------------|------------ \/\/ Cs | Undef | Tc=0: 0-255 | Tc=0: 0-255 | 0-255 \/\/ | | Tc=1: 1-63 | Tc=1: 1-63 | \/\/ ------------|-----------|-------------|-------------------|------------ \/\/ However, to keep it simple (and not depend on lossless mode), \/\/ we will only check the maximal range if (!ValidateValue(nDAC_Cs,0,255,_T(\"Conditioning table value \"),true,0)) return DECMARK_ERR; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DNL: \/\/ DNL (Define number of lines) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Ld m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Header length = %u\"),nLength); strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ NL m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Number of lines = %u\"),nTmpVal); strTmp.Format(_T(\" Number of lines = %u\"),nTmpVal); m_pLog->AddLine(strTmp); if (!ValidateValue(nTmpVal,1,65535,_T(\"Number of lines \"),true,1)) return DECMARK_ERR; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_EXP: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Le m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Header length = %u\"),nLength); strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); unsigned nEXP_Eh,nEXP_Ev; nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Eh,Ev nEXP_Eh = (nTmpVal & 0xF0) >> 4; nEXP_Ev = (nTmpVal & 0x0F); m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Expand horizontally = %u\"),nEXP_Eh); strTmp.Format(_T(\" Expand horizontally = %u\"),nEXP_Eh); m_pLog->AddLine(strTmp); \/\/XXX strTmp.Format(_T(\" Expand vertically = %u\"),nEXP_Ev); strTmp.Format(_T(\" Expand vertically = %u\"),nEXP_Ev); m_pLog->AddLine(strTmp); if (!ValidateValue(nEXP_Eh,0,1,_T(\"Expand horizontally \"),true,0)) return DECMARK_ERR; if (!ValidateValue(nEXP_Ev,0,1,_T(\"Expand vertically \"),true,0)) return DECMARK_ERR; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_SOF0: \/\/ SOF0 (Baseline DCT) case JFIF_SOF1: \/\/ SOF1 (Extended sequential) case JFIF_SOF2: \/\/ SOF2 (Progressive) case JFIF_SOF3: case JFIF_SOF5: case JFIF_SOF6: case JFIF_SOF7: case JFIF_SOF9: case JFIF_SOF10: case JFIF_SOF11: case JFIF_SOF13: case JFIF_SOF14: case JFIF_SOF15: \/\/ TODO: \/\/ - JFIF_DHP should be able to reuse the JFIF_SOF marker parsing \/\/ however as we don't support hierarchical image decode, we \/\/ would want to skip the update of class members. m_bStateSof = true; \/\/ Determine if this is a SOF mode that we support \/\/ At this time, we only support Baseline DCT & Extended Sequential Baseline DCT \/\/ (non-differential) with Huffman coding. Progressive, Lossless, \/\/ Differential and Arithmetic coded modes are not supported. m_bImgSofUnsupported = true; if (nCode == JFIF_SOF0) { m_bImgSofUnsupported = false; } if (nCode == JFIF_SOF1) { m_bImgSofUnsupported = false; } \/\/ For reference, note progressive scan files even though \/\/ we don't currently support their decode if (nCode == JFIF_SOF2) { m_bImgProgressive = true; } nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Lf m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Frame header length = %u\"),nLength); strTmp.Format(_T(\" Frame header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_nSofPrecision_P = Buf(m_nPos++); \/\/ P \/\/XXX strTmp.Format(_T(\" Precision

= %u\"),m_nSofPrecision_P); strTmp.Format(_T(\" Precision = %u\"),m_nSofPrecision_P); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofPrecision_P,2,16,_T(\"Precision

\"),true,8)) return DECMARK_ERR; m_nSofNumLines_Y = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Y m_nPos += 2; \/\/XXX strTmp.Format(_T(\" Number of Lines = %u\"),m_nSofNumLines_Y); strTmp.Format(_T(\" Number of Lines = %u\"),m_nSofNumLines_Y); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofNumLines_Y,0,65535,_T(\"Number of Lines \"),true,0)) return DECMARK_ERR; m_nSofSampsPerLine_X = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ X m_nPos += 2; \/\/XXX strTmp.Format(_T(\" Samples per Line = %u\"),m_nSofSampsPerLine_X); strTmp.Format(_T(\" Samples per Line = %u\"),m_nSofSampsPerLine_X); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofSampsPerLine_X,1,65535,_T(\"Samples per Line \"),true,1)) return DECMARK_ERR; strTmp.Format(_T(\" Image Size = %u x %u\"),m_nSofSampsPerLine_X,m_nSofNumLines_Y); m_pLog->AddLine(strTmp); \/\/ Determine orientation \/\/ m_nSofSampsPerLine_X = X \/\/ m_nSofNumLines_Y = Y m_eImgLandscape = ENUM_LANDSCAPE_YES; if (m_nSofNumLines_Y > m_nSofSampsPerLine_X) m_eImgLandscape = ENUM_LANDSCAPE_NO; strTmp.Format(_T(\" Raw Image Orientation = %s\"),(m_eImgLandscape==ENUM_LANDSCAPE_YES)?_T(\"Landscape\"):_T(\"Portrait\")); m_pLog->AddLine(strTmp); m_nSofNumComps_Nf = Buf(m_nPos++); \/\/ Nf, range 1..255 \/\/XXX strTmp.Format(_T(\" Number of Img components = %u\"),m_nSofNumComps_Nf); strTmp.Format(_T(\" Number of Img components = %u\"),m_nSofNumComps_Nf); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofNumComps_Nf,1,255,_T(\"Number of Img components \"),true,1)) return DECMARK_ERR; unsigned nCompIdent; unsigned anSofSampFact[MAX_SOF_COMP_NF]; m_nSofHorzSampFactMax_Hmax = 0; m_nSofVertSampFactMax_Vmax = 0; \/\/ Now clear the output image content (all components) \/\/ TODO: Migrate some of the bitmap allocation \/ clearing from \/\/ DecodeScanImg() into ResetImageContent() and call here \/\/m_pImgDec->ResetImageContent(); \/\/ Per JFIF v1.02: \/\/ - Nf = 1 or 3 \/\/ - C1 = Y \/\/ - C2 = Cb \/\/ - C3 = Cr for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = Buf(m_nPos++); \/\/ Ci, range 0..255 m_anSofQuantCompId[nCompInd] = nCompIdent; \/\/if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T(\"Component ID \"),true,0)) return DECMARK_ERR; anSofSampFact[nCompIdent] = Buf(m_nPos++); m_anSofQuantTblSel_Tqi[nCompIdent] = Buf(m_nPos++); \/\/ Tqi, range 0..3 \/\/if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T(\"Table Destination ID \"),true,0)) return DECMARK_ERR; \/\/ NOTE: We protect against bad input here as replication ratios are \/\/ determined later that depend on dividing by sampling factor (hence \/\/ possibility of div by 0). m_anSofHorzSampFact_Hi[nCompIdent] = (anSofSampFact[nCompIdent] & 0xF0) >> 4; \/\/ Hi, range 1..4 m_anSofVertSampFact_Vi[nCompIdent] = (anSofSampFact[nCompIdent] & 0x0F); \/\/ Vi, range 1..4 if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T(\"Horizontal Sampling Factor \"),true,1)) return DECMARK_ERR; if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T(\"Vertical Sampling Factor \"),true,1)) return DECMARK_ERR; } \/\/ Calculate max sampling factors for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; \/\/ Calculate maximum sampling factor for the SOF. This is only \/\/ used for later generation of m_strImgQuantCss an the SOF \/\/ reporting below. The CimgDecode block is responsible for \/\/ calculating the maximum sampling factor on a per-scan basis. m_nSofHorzSampFactMax_Hmax = max(m_nSofHorzSampFactMax_Hmax,m_anSofHorzSampFact_Hi[nCompIdent]); m_nSofVertSampFactMax_Vmax = max(m_nSofVertSampFactMax_Vmax,m_anSofVertSampFact_Vi[nCompIdent]); } \/\/ Report per-component sampling factors and quantization table selectors for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; \/\/ Create subsampling ratio \/\/ - Protect against division-by-zero CString strSubsampH = _T(\"?\"); CString strSubsampV = _T(\"?\"); if (m_anSofHorzSampFact_Hi[nCompIdent] > 0) { strSubsampH.Format(_T(\"%u\"),m_nSofHorzSampFactMax_Hmax\/m_anSofHorzSampFact_Hi[nCompIdent]); } if (m_anSofVertSampFact_Vi[nCompIdent] > 0) { strSubsampV.Format(_T(\"%u\"),m_nSofVertSampFactMax_Vmax\/m_anSofVertSampFact_Vi[nCompIdent]); } strFull.Format(_T(\" Component[%u]: \"),nCompInd); \/\/ Note i in Ci is 1-based \/\/XXX strTmp.Format(_T(\"ID=0x%02X, Samp Fac =0x%02X (Subsamp %u x %u), Quant Tbl Sel =0x%02X\"), strTmp.Format(_T(\"ID=0x%02X, Samp Fac=0x%02X (Subsamp %s x %s), Quant Tbl Sel=0x%02X\"), nCompIdent,anSofSampFact[nCompIdent], (LPCTSTR)strSubsampH,(LPCTSTR)strSubsampV, m_anSofQuantTblSel_Tqi[nCompIdent]); strFull += strTmp; \/\/ Mapping from component index (not ID) to colour channel per JFIF if (m_nSofNumComps_Nf == 1) { \/\/ Assume grayscale strFull += _T(\" (Lum: Y)\"); } else if (m_nSofNumComps_Nf == 3) { \/\/ Assume YCC if (nCompInd == SCAN_COMP_Y) { strFull += _T(\" (Lum: Y)\"); } else if (nCompInd == SCAN_COMP_CB) { strFull += _T(\" (Chrom: Cb)\"); } else if (nCompInd == SCAN_COMP_CR) { strFull += _T(\" (Chrom: Cr)\"); } } else if (m_nSofNumComps_Nf == 4) { \/\/ Assume YCCK if (nCompInd == 1) { strFull += _T(\" (Y)\"); } else if (nCompInd == 2) { strFull += _T(\" (Cb)\"); } else if (nCompInd == 3) { strFull += _T(\" (Cr)\"); } else if (nCompInd == 4) { strFull += _T(\" (K)\"); } } else { strFull += _T(\" (???)\"); \/\/ Unknown } m_pLog->AddLine(strFull); } \/\/ Test for bad input, clean up if bad for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T(\"Component ID \"),true,0)) return DECMARK_ERR; if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T(\"Table Destination ID \"),true,0)) return DECMARK_ERR; if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T(\"Horizontal Sampling Factor \"),true,1)) return DECMARK_ERR; if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T(\"Vertical Sampling Factor \"),true,1)) return DECMARK_ERR; } \/\/ Finally, assign the cleaned values to the decoder for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; \/\/ Store the DQT Table selection for the Image Decoder \/\/ Param values: Nf,Tqi \/\/ Param ranges: 1..255,0..3 \/\/ Note that the Image Decoder doesn't need to see the Component Identifiers bRet = m_pImgDec->SetDqtTables(nCompInd,m_anSofQuantTblSel_Tqi[nCompIdent]); DecodeErrCheck(bRet); \/\/ Store the Precision (to handle 12-bit decode) m_pImgDec->SetPrecision(m_nSofPrecision_P); } if (!m_bStateAbort) { \/\/ Set the component sampling factors (chroma subsampling) \/\/ FIXME: check ranging for (unsigned nCompInd=1;nCompInd<=m_nSofNumComps_Nf;nCompInd++) { \/\/ nCompInd is component index (1...Nf) \/\/ nCompIdent is Component Identifier (Ci) \/\/ Note that the Image Decoder doesn't need to see the Component Identifiers nCompIdent = m_anSofQuantCompId[nCompInd]; m_pImgDec->SetSofSampFactors(nCompInd,m_anSofHorzSampFact_Hi[nCompIdent],m_anSofVertSampFact_Vi[nCompIdent]); } \/\/ Now mark the image as been somewhat OK (ie. should \/\/ also be suitable for EmbeddedThumb() and PrepareSignature() m_bImgOK = true; m_bStateSofOk = true; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_COM: \/\/ COM nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); m_nPos+=2; strTmp.Format(_T(\" Comment length = %u\"),nLength); m_pLog->AddLine(strTmp); \/\/ Check for JPEG COM vulnerability \/\/ http:\/\/marc.info\/?l=bugtraq&m=109524346729948 \/\/ Note that the recovery is not very graceful. It will assume that the \/\/ field is actually zero-length, which will make the next byte trigger the \/\/ \"Expected marker 0xFF\" error message and probably abort. There is no \/\/ obvious way to if ( (nLength == 0) || (nLength == 1) ) { strTmp.Format(_T(\" JPEG Comment Field Vulnerability detected!\")); m_pLog->AddLineErr(strTmp); strTmp.Format(_T(\" Skipping data until next marker...\")); m_pLog->AddLineErr(strTmp); nLength = 2; bool bDoneSearch = false; unsigned nSkipStart = m_nPos; while (!bDoneSearch) { if (Buf(m_nPos) != 0xFF) { m_nPos++; } else { bDoneSearch = true; } if (m_nPos >= m_pWBuf->GetPosEof()) { bDoneSearch = true; } } strTmp.Format(_T(\" Skipped %u bytes\"),m_nPos - nSkipStart); m_pLog->AddLineErr(strTmp); \/\/ Break out of case statement break; } \/\/ Assume COM field valid length (ie. >= 2) strFull = _T(\" Comment=\"); m_strComment = _T(\"\"); for (unsigned ind=0;indAddLine(strFull); break; case JFIF_DHT: \/\/ DHT m_bStateDht = true; DecodeDHT(false); m_bStateDhtOk = true; break; case JFIF_SOS: \/\/ SOS unsigned long nPosScanStart; \/\/ Byte count at start of scan data segment m_bStateSos = true; \/\/ NOTE: Only want to capture position of first SOS \/\/ This should make other function such as AVI frame extract \/\/ more robust in case we get multiple SOS segments. \/\/ We assume that this value is reset when we start a new decode if (m_nPosSos == 0) { m_nPosSos = m_nPos-2; \/\/ Used for Extract. Want to include actual marker } nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); m_nPos+=2; \/\/ Ensure that we have seen proper markers before we try this one! if (!m_bStateSofOk) { strTmp.Format(_T(\" ERROR: SOS before valid SOF defined\")); m_pLog->AddLineErr(strTmp); return DECMARK_ERR; } strTmp.Format(_T(\" Scan header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_nSosNumCompScan_Ns = Buf(m_nPos++); \/\/ Ns, range 1..4 \/\/XXX strTmp.Format(_T(\" Number of image components = %u\"),m_nSosNumCompScan_Ns); strTmp.Format(_T(\" Number of img components = %u\"),m_nSosNumCompScan_Ns); m_pLog->AddLine(strTmp); \/\/ Just in case something got corrupted, don't want to get out \/\/ of range here. Note that this will be a hard abort, and \/\/ will not resume decoding. if (m_nSosNumCompScan_Ns > MAX_SOS_COMP_NS) { strTmp.Format(_T(\" ERROR: Scan decode does not support > %u components\"),MAX_SOS_COMP_NS); m_pLog->AddLineErr(strTmp); return DECMARK_ERR; } unsigned nSosCompSel_Cs; unsigned nSosHuffTblSel; unsigned nSosHuffTblSelDc_Td; unsigned nSosHuffTblSelAc_Ta; \/\/ Max range of components indices is between 1..4 for (unsigned int nScanCompInd=1;((nScanCompInd<=m_nSosNumCompScan_Ns) && (!m_bStateAbort));nScanCompInd++) { strFull.Format(_T(\" Component[%u]: \"),nScanCompInd); nSosCompSel_Cs = Buf(m_nPos++); \/\/ Cs, range 0..255 nSosHuffTblSel = Buf(m_nPos++); nSosHuffTblSelDc_Td = (nSosHuffTblSel & 0xf0)>>4; \/\/ Td, range 0..3 nSosHuffTblSelAc_Ta = (nSosHuffTblSel & 0x0f); \/\/ Ta, range 0..3 strTmp.Format(_T(\"selector=0x%02X, table=%u(DC),%u(AC)\"),nSosCompSel_Cs,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta); strFull += strTmp; m_pLog->AddLine(strFull); bRet = m_pImgDec->SetDhtTables(nScanCompInd,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta); DecodeErrCheck(bRet); } m_nSosSpectralStart_Ss = Buf(m_nPos++); m_nSosSpectralEnd_Se = Buf(m_nPos++); m_nSosSuccApprox_A = Buf(m_nPos++); strTmp.Format(_T(\" Spectral selection = %u .. %u\"),m_nSosSpectralStart_Ss,m_nSosSpectralEnd_Se); m_pLog->AddLine(strTmp); strTmp.Format(_T(\" Successive approximation = 0x%02X\"),m_nSosSuccApprox_A); m_pLog->AddLine(strTmp); if (m_pAppConfig->bOutputScanDump) { m_pLog->AddLine(_T(\"\")); m_pLog->AddLine(_T(\" Scan Data: (after bitstuff removed)\")); } \/\/ Save the scan data segment position nPosScanStart = m_nPos; \/\/ Skip over the Scan Data segment \/\/ Pass 1) Quick, allowing for bOutputScanDump to dump first 640B. \/\/ Pass 2) If bDecodeScanImg, we redo the process but in detail decoding. \/\/ FIXME: Not sure why, but if I skip over Pass 1 (eg if I leave in the \/\/ following line uncommented), then I get an error at the end of the \/\/ pass 2 decode (indicating that EOI marker not seen, and expecting \/\/ marker). \/\/ if (m_pAppConfig->bOutputScanDump) { \/\/ --- PASS 1 --- bool bSkipDone; unsigned nSkipCount; unsigned nSkipData; unsigned nSkipPos; bool bScanDumpTrunc; bSkipDone = false; nSkipCount = 0; nSkipPos = 0; bScanDumpTrunc = FALSE; strFull = _T(\"\"); while (!bSkipDone) { nSkipCount++; nSkipPos++; nSkipData = Buf(m_nPos++); if (nSkipData == 0xFF) { \/\/ this could either be a marker or a byte stuff nSkipData = Buf(m_nPos++); nSkipCount++; if (nSkipData == 0x00) { \/\/ Byte stuff nSkipData = 0xFF; } else if ((nSkipData >= JFIF_RST0) && (nSkipData <= JFIF_RST7)) { \/\/ Skip over } else { \/\/ Marker bSkipDone = true; m_nPos -= 2; } } if (m_pAppConfig->bOutputScanDump && (!bSkipDone) ) { \/\/ Only display 20 lines of scan data if (nSkipPos > 640) { if (!bScanDumpTrunc) { m_pLog->AddLineWarn(_T(\" WARNING: Dump truncated.\")); bScanDumpTrunc = TRUE; } } else { if ( ((nSkipPos-1) == 0) || (((nSkipPos-1) % 32) == 0) ) { strFull = _T(\" \"); } strTmp.Format(_T(\"%02x \"),nSkipData); strFull += strTmp; if (((nSkipPos-1) % 32) == 31) { m_pLog->AddLine(strFull); strFull = _T(\"\"); } } } \/\/ Did we run out of bytes? \/\/ FIXME: \/\/ NOTE: This line here doesn't allow us to attempt to \/\/ decode images that are missing EOI. Maybe this is \/\/ not the best solution here? Instead, we should be \/\/ checking m_nPos against file length? .. and not \/\/ return but \"break\". if (!m_pWBuf->GetBufOk()) { strTmp.Format(_T(\"ERROR: Ran out of buffer before EOI during phase 1 of Scan decode @ 0x%08X\"),m_nPos); m_pLog->AddLineErr(strTmp); break; } } m_pLog->AddLine(strFull); \/\/ } \/\/ --- PASS 2 --- \/\/ If the option is set, start parsing! if (m_pAppConfig->bDecodeScanImg && m_bImgSofUnsupported) { \/\/ SOF marker was of type we don't support, so skip decoding m_pLog->AddLineWarn(_T(\" NOTE: Scan parsing doesn't support this SOF mode.\")); #ifndef DEBUG_YCCK } else if (m_pAppConfig->bDecodeScanImg && (m_nSofNumComps_Nf == 4)) { m_pLog->AddLineWarn(_T(\" NOTE: Scan parsing doesn't support CMYK files yet.\")); #endif } else if (m_pAppConfig->bDecodeScanImg && !m_bImgSofUnsupported) { if (!m_bStateSofOk) { m_pLog->AddLineWarn(_T(\" NOTE: Scan decode disabled as SOF not decoded.\")); } else if (!m_bStateDqtOk) { m_pLog->AddLineWarn(_T(\" NOTE: Scan decode disabled as DQT not decoded.\")); } else if (!m_bStateDhtOk) { m_pLog->AddLineWarn(_T(\" NOTE: Scan decode disabled as DHT not decoded.\")); } else { m_pLog->AddLine(_T(\"\")); \/\/ Set the primary image details m_pImgDec->SetImageDetails(m_nSofSampsPerLine_X,m_nSofNumLines_Y, m_nSofNumComps_Nf,m_nSosNumCompScan_Ns,m_nImgRstEn,m_nImgRstInterval); \/\/ Only recalculate the scan decoding if we need to (i.e. file \/\/ changed, offset changed, scan option changed) \/\/ TODO: In order to decode multiple scans, we will need to alter the \/\/ way that m_pImgSrcDirty is set if (m_pImgSrcDirty) { m_pImgDec->DecodeScanImg(nPosScanStart,true,false); m_pImgSrcDirty = false; } } } m_bStateSosOk = true; break; case JFIF_DRI: unsigned nVal; nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3); \/\/ According to ITU-T spec B.2.4.4, we only expect \/\/ restart markers if DRI value is non-zero! m_nImgRstInterval = nVal; if (nVal != 0) { m_nImgRstEn = true; } else { m_nImgRstEn = false; } strTmp.Format(_T(\" interval = %u\"),m_nImgRstInterval); m_pLog->AddLine(strTmp); m_nPos += 4; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_EOI: \/\/ EOI m_pLog->AddLine(_T(\"\")); \/\/ Save the EOI file position \/\/ NOTE: If the file is missing the EOI, then this variable will be \/\/ set to mark the end of file. m_nPosEmbedEnd = m_nPos; m_nPosEoi = m_nPos; m_bStateEoi = true; return DECMARK_EOI; break; \/\/ Markers that are not yet supported in JPEGsnoop case JFIF_DHP: \/\/ Markers defined for future use \/ extensions case JFIF_JPG: case JFIF_JPG0: case JFIF_JPG1: case JFIF_JPG2: case JFIF_JPG3: case JFIF_JPG4: case JFIF_JPG5: case JFIF_JPG6: case JFIF_JPG7: case JFIF_JPG8: case JFIF_JPG9: case JFIF_JPG10: case JFIF_JPG11: case JFIF_JPG12: case JFIF_JPG13: case JFIF_TEM: \/\/ Unsupported marker \/\/ - Provide generic decode based on length nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Length strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(\" Skipping unsupported marker\")); m_nPos += nLength; break; case JFIF_RST0: case JFIF_RST1: case JFIF_RST2: case JFIF_RST3: case JFIF_RST4: case JFIF_RST5: case JFIF_RST6: case JFIF_RST7: \/\/ We don't expect to see restart markers outside the entropy coded segment. \/\/ NOTE: RST# are standalone markers, so no length indicator exists \/\/ But for the sake of robustness, we can check here to see if treating \/\/ as a standalone marker will arrive at another marker (ie. OK). If not, \/\/ proceed to assume there is a length indicator. strTmp.Format(_T(\" WARNING: Restart marker [0xFF%02X] detected outside scan\"),nCode); m_pLog->AddLineWarn(strTmp); if (!m_pAppConfig->bRelaxedParsing) { \/\/ Abort m_pLog->AddLineErr(_T(\" Stopping decode\")); m_pLog->AddLine(_T(\" Use [Img Search Fwd\/Rev] to locate other valid embedded JPEGs\")); return DECMARK_ERR; } else { \/\/ Ignore \/\/ Check to see if standalone marker treatment looks OK if (Buf(m_nPos+2) == 0xFF) { \/\/ Looks like standalone m_pLog->AddLineWarn(_T(\" Ignoring standalone marker. Proceeding with decode.\")); m_nPos += 2; } else { \/\/ Looks like marker with length nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(\" Skipping marker\")); m_nPos += nLength; } } break; default: strTmp.Format(_T(\" WARNING: Unknown marker [0xFF%02X]\"),nCode); m_pLog->AddLineWarn(strTmp); if (!m_pAppConfig->bRelaxedParsing) { \/\/ Abort m_pLog->AddLineErr(_T(\" Stopping decode\")); m_pLog->AddLine(_T(\" Use [Img Search Fwd\/Rev] to locate other valid embedded JPEGs\")); return DECMARK_ERR; } else { \/\/ Skip nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(\" Skipping marker\")); m_nPos += nLength; } } \/\/ Add white-space between each marker m_pLog->AddLine(_T(\" \")); \/\/ If we decided to abort for any reason, make sure we trap it now. \/\/ This will stop the ProcessFile() while loop. We can set m_bStateAbort \/\/ if user says that they want to stop. if (m_bStateAbort) { return DECMARK_ERR; } return DECMARK_OK; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":935,"input":"static long bcm_char_ioctl(struct file *filp, UINT cmd, ULONG arg) { struct bcm_tarang_data *pTarang = filp->private_data; void __user *argp = (void __user *)arg; struct bcm_mini_adapter *Adapter = pTarang->Adapter; INT Status = STATUS_FAILURE; int timeout = 0; struct bcm_ioctl_buffer IoBuffer; int bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Parameters Passed to control IOCTL cmd=0x%X arg=0x%lX\", cmd, arg); if (_IOC_TYPE(cmd) != BCM_IOCTL) return -EFAULT; if (_IOC_DIR(cmd) & _IOC_READ) Status = !access_ok(VERIFY_WRITE, argp, _IOC_SIZE(cmd)); else if (_IOC_DIR(cmd) & _IOC_WRITE) Status = !access_ok(VERIFY_READ, argp, _IOC_SIZE(cmd)); else if (_IOC_NONE == (_IOC_DIR(cmd) & _IOC_NONE)) Status = STATUS_SUCCESS; if (Status) return -EFAULT; if (Adapter->device_removed) return -EFAULT; if (FALSE == Adapter->fw_download_done) { switch (cmd) { case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: case IOCTL_BCM_GPIO_SET_REQUEST: case IOCTL_BCM_GPIO_STATUS_REQUEST: return -EACCES; default: break; } } Status = vendorextnIoctl(Adapter, cmd, arg); if (Status != CONTINUE_COMMON_PATH) return Status; switch (cmd) { \/* Rdms for Swin Idle... *\/ case IOCTL_BCM_REGISTER_READ_PRIVATE: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff; UINT Bufflen; u16 temp_value; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } Bufflen = IoBuffer.OutputLength; temp_value = 4 - (Bufflen % 4); Bufflen += temp_value % 4; temp_buff = kmalloc(Bufflen, GFP_KERNEL); if (!temp_buff) return -ENOMEM; bytes = rdmalt(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, Bufflen); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE_PRIVATE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; \/* Get WrmBuffer structure *\/ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); return -EFAULT; } Status = wrmalt(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Done\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Failed\\n\"); Status = -EFAULT; } break; } case IOCTL_BCM_REGISTER_READ: case IOCTL_BCM_EEPROM_REGISTER_READ: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff = NULL; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle Mode, Blocking Rdms\\n\"); return -EACCES; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } temp_buff = kmalloc(IoBuffer.OutputLength, GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; if ((((ULONG)sRdmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sRdmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM Done On invalid Address : %x Access Denied.\\n\", (int)sRdmBuffer.Register); kfree(temp_buff); return -EINVAL; } uiTempVar = sRdmBuffer.Register & EEPROM_REJECT_MASK; bytes = rdmaltWithLock(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, IoBuffer.OutputLength); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE: case IOCTL_BCM_EEPROM_REGISTER_WRITE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle Mode, Blocking Wrms\\n\"); return -EACCES; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; \/* Get WrmBuffer structure *\/ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if ((((ULONG)sWrmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sWrmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Done On invalid Address : %x Access Denied.\\n\", (int)sWrmBuffer.Register); return -EINVAL; } uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); return -EFAULT; } Status = wrmaltWithLock(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sWrmBuffer.Length); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, \"WRM Done\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Failed\\n\"); Status = -EFAULT; } break; } case IOCTL_BCM_GPIO_SET_REQUEST: { UCHAR ucResetValue[4]; UINT value = 0; UINT uiBit = 0; UINT uiOperation = 0; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO Can't be set\/clear in Low power Mode\"); return -EACCES; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; uiOperation = gpio_info.uiGpioValue; value = (1< is not correspond to LED !!!\", value); Status = -EINVAL; break; } \/* Set - setting 1 *\/ if (uiOperation) { \/* Set the gpio output register *\/ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Set the GPIO bit\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Failed to set the %dth GPIO\\n\", uiBit); break; } } else { \/* Set the gpio output register *\/ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Set the GPIO bit\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Failed to clear the %dth GPIO\\n\", uiBit); break; } } bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO_MODE_REGISTER read failed\"); break; } else { Status = STATUS_SUCCESS; } \/* Set the gpio mode register to output *\/ *(UINT *)ucResetValue |= (1<IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO Can't be set\/clear in Low power Mode\"); Status = -EACCES; break; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(threadReq)) return -EINVAL; if (copy_from_user(&threadReq, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; \/* if LED thread is running(Actively or Inactively) set it state to make inactive *\/ if (Adapter->LEDInfo.led_thread_running) { if (threadReq.ThreadState == LED_THREAD_ACTIVATION_REQ) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Activating thread req\"); Adapter->DriverState = LED_THREAD_ACTIVE; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DeActivating Thread req.....\"); Adapter->DriverState = LED_THREAD_INACTIVE; } \/* signal thread. *\/ wake_up(&Adapter->LEDInfo.notify_led_event); } } break; case IOCTL_BCM_GPIO_STATUS_REQUEST: { ULONG uiBit = 0; UCHAR ucRead[4]; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EACCES; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; \/* Set the gpio output register *\/ bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucRead, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM Failed\\n\"); return Status; } else { Status = STATUS_SUCCESS; } } break; case IOCTL_BCM_GPIO_MULTI_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_info gpio_multi_info[MAX_IDX]; struct bcm_gpio_multi_info *pgpio_multi_info = (struct bcm_gpio_multi_info *)gpio_multi_info; memset(pgpio_multi_info, 0, MAX_IDX * sizeof(struct bcm_gpio_multi_info)); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_info)) return -EINVAL; if (copy_from_user(&gpio_multi_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_info[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!\", pgpio_multi_info[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } \/* Set the gpio output register *\/ if ((pgpio_multi_info[WIMAX_IDX].uiGPIOMask) & (pgpio_multi_info[WIMAX_IDX].uiGPIOCommand)) { \/* Set 1's in GPIO OUTPUT REGISTER *\/ *(UINT *)ucResetValue = pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & pgpio_multi_info[WIMAX_IDX].uiGPIOValue; if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to BCM_GPIO_OUTPUT_SET_REG Failed.\"); return Status; } \/* Clear to 0's in GPIO OUTPUT REGISTER *\/ *(UINT *)ucResetValue = (pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & (~(pgpio_multi_info[WIMAX_IDX].uiGPIOValue))); if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to BCM_GPIO_OUTPUT_CLR_REG Failed.\"); return Status; } } if (pgpio_multi_info[WIMAX_IDX].uiGPIOMask) { bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM to GPIO_PIN_STATE_REGISTER Failed.\"); return Status; } else { Status = STATUS_SUCCESS; } pgpio_multi_info[WIMAX_IDX].uiGPIOValue = (*(UINT *)ucResetValue & pgpio_multi_info[WIMAX_IDX].uiGPIOMask); } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_info, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed while copying Content to IOBufer for user space err:%d\", Status); return -EFAULT; } } break; case IOCTL_BCM_GPIO_MODE_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_mode gpio_multi_mode[MAX_IDX]; struct bcm_gpio_multi_mode *pgpio_multi_mode = (struct bcm_gpio_multi_mode *)gpio_multi_mode; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_mode)) return -EINVAL; if (copy_from_user(&gpio_multi_mode, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Read of GPIO_MODE_REGISTER failed\"); return Status; } else { Status = STATUS_SUCCESS; } \/* Validating the request *\/ if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!\", pgpio_multi_mode[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } if (pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) { \/* write all OUT's (1's) *\/ *(UINT *) ucResetValue |= (pgpio_multi_mode[WIMAX_IDX].uiGPIOMode & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); \/* write all IN's (0's) *\/ *(UINT *) ucResetValue &= ~((~pgpio_multi_mode[WIMAX_IDX].uiGPIOMode) & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); \/* Currently implemented return the modes of all GPIO's * else needs to bit AND with mask *\/ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM to GPIO_MODE_REGISTER Done\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to GPIO_MODE_REGISTER Failed\"); Status = -EFAULT; break; } } else { \/* if uiGPIOMask is 0 then return mode register configuration *\/ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_mode, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed while copying Content to IOBufer for user space err:%d\", Status); return -EFAULT; } } break; case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: { PVOID pvBuffer = NULL; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(struct bcm_link_request)) return -EINVAL; if (IoBuffer.InputLength > MAX_CNTL_PKT_SIZE) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); down(&Adapter->LowPowerModeSync); Status = wait_event_interruptible_timeout(Adapter->lowpower_mode_wait_queue, !Adapter->bPreparingForLowPowerMode, (1 * HZ)); if (Status == -ERESTARTSYS) goto cntrlEnd; if (Adapter->bPreparingForLowPowerMode) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Preparing Idle Mode is still True - Hence Rejecting control message\\n\"); Status = STATUS_FAILURE; goto cntrlEnd; } Status = CopyBufferToControlPacket(Adapter, (PVOID)pvBuffer); cntrlEnd: up(&Adapter->LowPowerModeSync); kfree(pvBuffer); break; } case IOCTL_BCM_BUFFER_DOWNLOAD_START: { if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read\/Write is in progress\\n\"); return -EACCES; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Starting the firmware download PID =0x%x!!!!\\n\", current->pid); if (down_trylock(&Adapter->fw_download_sema)) return -EBUSY; Adapter->bBinDownloaded = FALSE; Adapter->fw_download_process_pid = current->pid; Adapter->bCfgDownloaded = FALSE; Adapter->fw_download_done = FALSE; netif_carrier_off(Adapter->dev); netif_stop_queue(Adapter->dev); Status = reset_card_proc(Adapter); if (Status) { pr_err(PFX \"%s: reset_card_proc Failed!\\n\", Adapter->dev->name); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } mdelay(10); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD: { struct bcm_firmware_info *psFwInfo = NULL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Starting the firmware download PID =0x%x!!!!\\n\", current->pid); if (!down_trylock(&Adapter->fw_download_sema)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Invalid way to download buffer. Use Start and then call this!!!\\n\"); up(&Adapter->fw_download_sema); Status = -EINVAL; return Status; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { up(&Adapter->fw_download_sema); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Length for FW DLD is : %lx\\n\", IoBuffer.InputLength); if (IoBuffer.InputLength > sizeof(struct bcm_firmware_info)) { up(&Adapter->fw_download_sema); return -EINVAL; } psFwInfo = kmalloc(sizeof(*psFwInfo), GFP_KERNEL); if (!psFwInfo) { up(&Adapter->fw_download_sema); return -ENOMEM; } if (copy_from_user(psFwInfo, IoBuffer.InputBuffer, IoBuffer.InputLength)) { up(&Adapter->fw_download_sema); kfree(psFwInfo); return -EFAULT; } if (!psFwInfo->pvMappedFirmwareAddress || (psFwInfo->u32FirmwareLength == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Something else is wrong %lu\\n\", psFwInfo->u32FirmwareLength); up(&Adapter->fw_download_sema); kfree(psFwInfo); Status = -EINVAL; return Status; } Status = bcm_ioctl_fw_download(Adapter, psFwInfo); if (Status != STATUS_SUCCESS) { if (psFwInfo->u32StartingAddress == CONFIG_BEGIN_ADDR) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL: Configuration File Upload Failed\\n\"); else BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL: Firmware File Upload Failed\\n\"); \/* up(&Adapter->fw_download_sema); *\/ if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = DRIVER_INIT; Adapter->LEDInfo.bLedInitDone = FALSE; wake_up(&Adapter->LEDInfo.notify_led_event); } } if (Status != STATUS_SUCCESS) up(&Adapter->fw_download_sema); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, \"IOCTL: Firmware File Uploaded\\n\"); kfree(psFwInfo); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD_STOP: { if (!down_trylock(&Adapter->fw_download_sema)) { up(&Adapter->fw_download_sema); return -EINVAL; } if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"FW download blocked as EEPROM Read\/Write is in progress\\n\"); up(&Adapter->fw_download_sema); return -EACCES; } Adapter->bBinDownloaded = TRUE; Adapter->bCfgDownloaded = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->downloadDDR = 0; \/* setting the Mips to Run *\/ Status = run_card_proc(Adapter); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Firm Download Failed\\n\"); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Firm Download Over...\\n\"); } mdelay(10); \/* Wait for MailBox Interrupt *\/ if (StartInterruptUrb((struct bcm_interface_adapter *)Adapter->pvInterfaceAdapter)) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Unable to send interrupt...\\n\"); timeout = 5*HZ; Adapter->waiting_to_fw_download_done = FALSE; wait_event_timeout(Adapter->ioctl_fw_dnld_wait_queue, Adapter->waiting_to_fw_download_done, timeout); Adapter->fw_download_process_pid = INVALID_PID; Adapter->fw_download_done = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->PrevNumRecvDescs = 0; atomic_set(&Adapter->cntrlpktCnt, 0); Adapter->LinkUpStatus = 0; Adapter->LinkStatus = 0; if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = FW_DOWNLOAD_DONE; wake_up(&Adapter->LEDInfo.notify_led_event); } if (!timeout) Status = -ENODEV; up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BE_BUCKET_SIZE: Status = 0; if (get_user(Adapter->BEBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_RTPS_BUCKET_SIZE: Status = 0; if (get_user(Adapter->rtPSBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_CHIP_RESET: { INT NVMAccess = down_trylock(&Adapter->NVMRdmWrmLock); if (NVMAccess) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \" IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read\/Write is in progress\\n\"); return -EACCES; } down(&Adapter->RxAppControlQueuelock); Status = reset_card_proc(Adapter); flushAllAppQ(); up(&Adapter->RxAppControlQueuelock); up(&Adapter->NVMRdmWrmLock); ResetCounters(Adapter); break; } case IOCTL_QOS_THRESHOLD: { USHORT uiLoopIndex; Status = 0; for (uiLoopIndex = 0; uiLoopIndex < NO_OF_QUEUES; uiLoopIndex++) { if (get_user(Adapter->PackInfo[uiLoopIndex].uiThreshold, (unsigned long __user *)arg)) { Status = -EFAULT; break; } } break; } case IOCTL_DUMP_PACKET_INFO: DumpPackInfo(Adapter); DumpPhsRules(&Adapter->stBCMPhsContext); Status = STATUS_SUCCESS; break; case IOCTL_GET_PACK_INFO: if (copy_to_user(argp, &Adapter->PackInfo, sizeof(struct bcm_packet_info)*NO_OF_QUEUES)) return -EFAULT; Status = STATUS_SUCCESS; break; case IOCTL_BCM_SWITCH_TRANSFER_MODE: { UINT uiData = 0; if (copy_from_user(&uiData, argp, sizeof(UINT))) return -EFAULT; if (uiData) { \/* Allow All Packets *\/ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SWITCH_TRANSFER_MODE: ETH_PACKET_TUNNELING_MODE\\n\"); Adapter->TransferMode = ETH_PACKET_TUNNELING_MODE; } else { \/* Allow IP only Packets *\/ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SWITCH_TRANSFER_MODE: IP_PACKET_ONLY_MODE\\n\"); Adapter->TransferMode = IP_PACKET_ONLY_MODE; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_DRIVER_VERSION: { ulong len; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; len = min_t(ulong, IoBuffer.OutputLength, strlen(DRV_VERSION) + 1); if (copy_to_user(IoBuffer.OutputBuffer, DRV_VERSION, len)) return -EFAULT; Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_CURRENT_STATUS: { struct bcm_link_state link_state; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"copy_from_user failed..\\n\"); return -EFAULT; } if (IoBuffer.OutputLength != sizeof(link_state)) { Status = -EINVAL; break; } memset(&link_state, 0, sizeof(link_state)); link_state.bIdleMode = Adapter->IdleMode; link_state.bShutdownMode = Adapter->bShutStatus; link_state.ucLinkStatus = Adapter->LinkStatus; if (copy_to_user(IoBuffer.OutputBuffer, &link_state, min_t(size_t, sizeof(link_state), IoBuffer.OutputLength))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy_to_user Failed..\\n\"); return -EFAULT; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_SET_MAC_TRACING: { UINT tracing_flag; \/* copy ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&tracing_flag, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if (tracing_flag) Adapter->pTarangs->MacTracingEnabled = TRUE; else Adapter->pTarangs->MacTracingEnabled = FALSE; break; } case IOCTL_BCM_GET_DSX_INDICATION: { ULONG ulSFId = 0; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_add_indication_alt)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Mismatch req: %lx needed is =0x%zx!!!\", IoBuffer.OutputLength, sizeof(struct bcm_add_indication_alt)); return -EINVAL; } if (copy_from_user(&ulSFId, IoBuffer.InputBuffer, sizeof(ulSFId))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Get DSX Data SF ID is =%lx\\n\", ulSFId); get_dsx_sf_data_to_application(Adapter, ulSFId, IoBuffer.OutputBuffer); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_GET_HOST_MIBS: { PVOID temp_buff; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_host_stats_mibs)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Length Check failed %lu %zd\\n\", IoBuffer.OutputLength, sizeof(struct bcm_host_stats_mibs)); return -EINVAL; } \/* FIXME: HOST_STATS are too big for kmalloc (122048)! *\/ temp_buff = kzalloc(sizeof(struct bcm_host_stats_mibs), GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; Status = ProcessGetHostMibs(Adapter, temp_buff); GetDroppedAppCntrlPktMibs(temp_buff, pTarang); if (Status != STATUS_FAILURE) if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, sizeof(struct bcm_host_stats_mibs))) { kfree(temp_buff); return -EFAULT; } kfree(temp_buff); break; } case IOCTL_BCM_WAKE_UP_DEVICE_FROM_IDLE: if ((FALSE == Adapter->bTriedToWakeUpFromlowPowerMode) && (TRUE == Adapter->IdleMode)) { Adapter->usIdleModePattern = ABORT_IDLE_MODE; Adapter->bWakeUpDevice = TRUE; wake_up(&Adapter->process_rx_cntrlpkt); } Status = STATUS_SUCCESS; break; case IOCTL_BCM_BULK_WRM: { struct bcm_bulk_wrm_buffer *pBulkBuffer; UINT uiTempVar = 0; PCHAR pvBuffer = NULL; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle\/Shutdown Mode, Blocking Wrms\\n\"); Status = -EACCES; break; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(ULONG) * 2) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); pBulkBuffer = (struct bcm_bulk_wrm_buffer *)pvBuffer; if (((ULONG)pBulkBuffer->Register & 0x0F000000) != 0x0F000000 || ((ULONG)pBulkBuffer->Register & 0x3)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Done On invalid Address : %x Access Denied.\\n\", (int)pBulkBuffer->Register); kfree(pvBuffer); Status = -EINVAL; break; } uiTempVar = pBulkBuffer->Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize)&VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { kfree(pvBuffer); BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); Status = -EFAULT; break; } if (pBulkBuffer->SwapEndian == FALSE) Status = wrmWithLock(Adapter, (UINT)pBulkBuffer->Register, (PCHAR)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); else Status = wrmaltWithLock(Adapter, (UINT)pBulkBuffer->Register, (PUINT)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); if (Status != STATUS_SUCCESS) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Failed\\n\"); kfree(pvBuffer); break; } case IOCTL_BCM_GET_NVM_SIZE: if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (Adapter->eNVMType == NVM_EEPROM || Adapter->eNVMType == NVM_FLASH) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiNVMDSDSize, sizeof(UINT))) return -EFAULT; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_CAL_INIT: { UINT uiSectorSize = 0 ; if (Adapter->eNVMType == NVM_FLASH) { if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&uiSectorSize, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if ((uiSectorSize < MIN_SECTOR_SIZE) || (uiSectorSize > MAX_SECTOR_SIZE)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if (IsFlash2x(Adapter)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if ((TRUE == Adapter->bShutStatus) || (TRUE == Adapter->IdleMode)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device is in Idle\/Shutdown Mode\\n\"); return -EACCES; } Adapter->uiSectorSize = uiSectorSize; BcmUpdateSectorSize(Adapter, Adapter->uiSectorSize); } } Status = STATUS_SUCCESS; } else { Status = STATUS_FAILURE; } } break; case IOCTL_BCM_SET_DEBUG: #ifdef DEBUG { struct bcm_user_debug_state sUserDebugState; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"In SET_DEBUG ioctl\\n\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&sUserDebugState, IoBuffer.InputBuffer, sizeof(struct bcm_user_debug_state))) return -EFAULT; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL_BCM_SET_DEBUG: OnOff=%d Type = 0x%x \", sUserDebugState.OnOff, sUserDebugState.Type); \/* sUserDebugState.Subtype <<= 1; *\/ sUserDebugState.Subtype = 1 << sUserDebugState.Subtype; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"actual Subtype=0x%x\\n\", sUserDebugState.Subtype); \/* Update new 'DebugState' in the Adapter *\/ Adapter->stDebugState.type |= sUserDebugState.Type; \/* Subtype: A bitmap of 32 bits for Subtype per Type. * Valid indexes in 'subtype' array: 1,2,4,8 * corresponding to valid Type values. Hence we can use the 'Type' field * as the index value, ignoring the array entries 0,3,5,6,7 ! *\/ if (sUserDebugState.OnOff) Adapter->stDebugState.subtype[sUserDebugState.Type] |= sUserDebugState.Subtype; else Adapter->stDebugState.subtype[sUserDebugState.Type] &= ~sUserDebugState.Subtype; BCM_SHOW_DEBUG_BITMAP(Adapter); } #endif break; case IOCTL_BCM_NVM_READ: case IOCTL_BCM_NVM_WRITE: { struct bcm_nvm_readwrite stNVMReadWrite; PUCHAR pReadData = NULL; ULONG ulDSDMagicNumInUsrBuff = 0; struct timeval tv0, tv1; memset(&tv0, 0, sizeof(struct timeval)); memset(&tv1, 0, sizeof(struct timeval)); if ((Adapter->eNVMType == NVM_FLASH) && (Adapter->uiFlashLayoutMajorVersion == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"The Flash Control Section is Corrupted. Hence Rejection on NVM Read\/Write\\n\"); return -EFAULT; } if (IsFlash2x(Adapter)) { if ((Adapter->eActiveDSD != DSD0) && (Adapter->eActiveDSD != DSD1) && (Adapter->eActiveDSD != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"No DSD is active..hence NVM Command is blocked\"); return STATUS_FAILURE; } } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&stNVMReadWrite, (IOCTL_BCM_NVM_READ == cmd) ? IoBuffer.OutputBuffer : IoBuffer.InputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; \/* * Deny the access if the offset crosses the cal area limit. *\/ if (stNVMReadWrite.uiNumBytes > Adapter->uiNVMDSDSize) return STATUS_FAILURE; if (stNVMReadWrite.uiOffset > Adapter->uiNVMDSDSize - stNVMReadWrite.uiNumBytes) { \/* BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,\"Can't allow access beyond NVM Size: 0x%x 0x%x\\n\", stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); *\/ return STATUS_FAILURE; } pReadData = memdup_user(stNVMReadWrite.pBuffer, stNVMReadWrite.uiNumBytes); if (IS_ERR(pReadData)) return PTR_ERR(pReadData); do_gettimeofday(&tv0); if (IOCTL_BCM_NVM_READ == cmd) { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Status = BeceemNVMRead(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } if (copy_to_user(stNVMReadWrite.pBuffer, pReadData, stNVMReadWrite.uiNumBytes)) { kfree(pReadData); return -EFAULT; } } else { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Adapter->bHeaderChangeAllowed = TRUE; if (IsFlash2x(Adapter)) { \/* * New Requirement:- * DSD section updation will be allowed in two case:- * 1. if DSD sig is present in DSD header means dongle is ok and updation is fruitfull * 2. if point 1 failes then user buff should have DSD sig. this point ensures that if dongle is * corrupted then user space program first modify the DSD header with valid DSD sig so * that this as well as further write may be worthwhile. * * This restriction has been put assuming that if DSD sig is corrupted, DSD * data won't be considered valid. *\/ Status = BcmFlash2xCorruptSig(Adapter, Adapter->eActiveDSD); if (Status != STATUS_SUCCESS) { if (((stNVMReadWrite.uiOffset + stNVMReadWrite.uiNumBytes) != Adapter->uiNVMDSDSize) || (stNVMReadWrite.uiNumBytes < SIGNATURE_SIZE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DSD Sig is present neither in Flash nor User provided Input..\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } ulDSDMagicNumInUsrBuff = ntohl(*(PUINT)(pReadData + stNVMReadWrite.uiNumBytes - SIGNATURE_SIZE)); if (ulDSDMagicNumInUsrBuff != DSD_IMAGE_MAGIC_NUMBER) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DSD Sig is present neither in Flash nor User provided Input..\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } } } Status = BeceemNVMWrite(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes, stNVMReadWrite.bVerify); if (IsFlash2x(Adapter)) BcmFlash2xWriteSig(Adapter, Adapter->eActiveDSD); Adapter->bHeaderChangeAllowed = FALSE; up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } } do_gettimeofday(&tv1); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \" timetaken by Write\/read :%ld msec\\n\", (tv1.tv_sec - tv0.tv_sec)*1000 + (tv1.tv_usec - tv0.tv_usec)\/1000); kfree(pReadData); return STATUS_SUCCESS; } case IOCTL_BCM_FLASH2X_SECTION_READ: { struct bcm_flash2x_readwrite sFlash2xRead = {0}; PUCHAR pReadBuff = NULL ; UINT NOB = 0; UINT BuffSize = 0; UINT ReadBytes = 0; UINT ReadOffset = 0; void __user *OutPutBuff; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_FLASH2X_SECTION_READ Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; \/* Reading FLASH 2.x READ structure *\/ if (copy_from_user(&sFlash2xRead, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.Section :%x\", sFlash2xRead.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.offset :%x\", sFlash2xRead.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.numOfBytes :%x\", sFlash2xRead.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.bVerify :%x\\n\", sFlash2xRead.bVerify); \/* This was internal to driver for raw read. now it has ben exposed to user space app. *\/ if (validateFlash2xReadWrite(Adapter, &sFlash2xRead) == FALSE) return STATUS_FAILURE; NOB = sFlash2xRead.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB; ReadOffset = sFlash2xRead.offset ; OutPutBuff = IoBuffer.OutputBuffer; pReadBuff = (PCHAR)kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory allocation failed for Flash 2.x Read Structure\"); return -ENOMEM; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EACCES; } while (NOB) { if (NOB > Adapter->uiSectorSize) ReadBytes = Adapter->uiSectorSize; else ReadBytes = NOB; \/* Reading the data from Flash 2.x *\/ Status = BcmFlash2xBulkRead(Adapter, (PUINT)pReadBuff, sFlash2xRead.Section, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Flash 2x read err with Status :%d\", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Copy to use failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes ; } } up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); } break; case IOCTL_BCM_FLASH2X_SECTION_WRITE: { struct bcm_flash2x_readwrite sFlash2xWrite = {0}; PUCHAR pWriteBuff; void __user *InputAddr; UINT NOB = 0; UINT BuffSize = 0; UINT WriteOffset = 0; UINT WriteBytes = 0; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } \/* First make this False so that we can enable the Sector Permission Check in BeceemFlashBulkWrite *\/ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_FLASH2X_SECTION_WRITE Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; \/* Reading FLASH 2.x READ structure *\/ if (copy_from_user(&sFlash2xWrite, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.Section :%x\", sFlash2xWrite.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.offset :%d\", sFlash2xWrite.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.numOfBytes :%x\", sFlash2xWrite.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.bVerify :%x\\n\", sFlash2xWrite.bVerify); if ((sFlash2xWrite.Section != VSA0) && (sFlash2xWrite.Section != VSA1) && (sFlash2xWrite.Section != VSA2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Only VSA write is allowed\"); return -EINVAL; } if (validateFlash2xReadWrite(Adapter, &sFlash2xWrite) == FALSE) return STATUS_FAILURE; InputAddr = sFlash2xWrite.pDataBuff; WriteOffset = sFlash2xWrite.offset; NOB = sFlash2xWrite.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB ; pWriteBuff = kmalloc(BuffSize, GFP_KERNEL); if (pWriteBuff == NULL) return -ENOMEM; \/* extracting the remainder of the given offset. *\/ WriteBytes = Adapter->uiSectorSize; if (WriteOffset % Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize - (WriteOffset % Adapter->uiSectorSize); if (NOB < WriteBytes) WriteBytes = NOB; down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EACCES; } BcmFlash2xCorruptSig(Adapter, sFlash2xWrite.Section); do { Status = copy_from_user(pWriteBuff, InputAddr, WriteBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy to user failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EFAULT; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pWriteBuff, WriteBytes); \/* Writing the data from Flash 2.x *\/ Status = BcmFlash2xBulkWrite(Adapter, (PUINT)pWriteBuff, sFlash2xWrite.Section, WriteOffset, WriteBytes, sFlash2xWrite.bVerify); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash 2x read err with Status :%d\", Status); break; } NOB = NOB - WriteBytes; if (NOB) { WriteOffset = WriteOffset + WriteBytes; InputAddr = InputAddr + WriteBytes; if (NOB > Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize; else WriteBytes = NOB; } } while (NOB > 0); BcmFlash2xWriteSig(Adapter, sFlash2xWrite.Section); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); } break; case IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP: { struct bcm_flash2x_bitmap *psFlash2xBitMap; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_flash2x_bitmap)) return -EINVAL; psFlash2xBitMap = kzalloc(sizeof(struct bcm_flash2x_bitmap), GFP_KERNEL); if (psFlash2xBitMap == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory is not available\"); return -ENOMEM; } \/* Reading the Flash Sectio Bit map *\/ down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(psFlash2xBitMap); return -EACCES; } BcmGetFlash2xSectionalBitMap(Adapter, psFlash2xBitMap); up(&Adapter->NVMRdmWrmLock); if (copy_to_user(IoBuffer.OutputBuffer, psFlash2xBitMap, sizeof(struct bcm_flash2x_bitmap))) { kfree(psFlash2xBitMap); return -EFAULT; } kfree(psFlash2xBitMap); } break; case IOCTL_BCM_SET_ACTIVE_SECTION: { enum bcm_flash2x_section_val eFlash2xSectionVal = 0; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SET_ACTIVE_SECTION Called\"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of flash section val failed\"); return -EFAULT; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Status = BcmSetActiveSection(Adapter, eFlash2xSectionVal); if (Status) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed to make it's priority Highest. Status %d\", Status); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_IDENTIFY_ACTIVE_SECTION: { \/* Right Now we are taking care of only DSD *\/ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_IDENTIFY_ACTIVE_SECTION called\"); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_COPY_SECTION: { struct bcm_flash2x_copy_section sCopySectStrut = {0}; Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_COPY_SECTION Called\"); Adapter->bAllDSDWriteAllow = FALSE; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed Status :%d\", Status); return -EFAULT; } Status = copy_from_user(&sCopySectStrut, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_copy_section)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of Copy_Section_Struct failed with Status :%d\", Status); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Source SEction :%x\", sCopySectStrut.SrcSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Destination SEction :%x\", sCopySectStrut.DstSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"offset :%x\", sCopySectStrut.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"NOB :%x\", sCopySectStrut.numOfBytes); if (IsSectionExistInFlash(Adapter, sCopySectStrut.SrcSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Source Section<%x> does not exixt in Flash \", sCopySectStrut.SrcSection); return -EINVAL; } if (IsSectionExistInFlash(Adapter, sCopySectStrut.DstSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Destinatio Section<%x> does not exixt in Flash \", sCopySectStrut.DstSection); return -EINVAL; } if (sCopySectStrut.SrcSection == sCopySectStrut.DstSection) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Source and Destination section should be different\"); return -EINVAL; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } if (sCopySectStrut.SrcSection == ISO_IMAGE1 || sCopySectStrut.SrcSection == ISO_IMAGE2) { if (IsNonCDLessDevice(Adapter)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device is Non-CDLess hence won't have ISO !!\"); Status = -EINVAL; } else if (sCopySectStrut.numOfBytes == 0) { Status = BcmCopyISO(Adapter, sCopySectStrut); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Partial Copy of ISO section is not Allowed..\"); Status = STATUS_FAILURE; } up(&Adapter->NVMRdmWrmLock); return Status; } Status = BcmCopySection(Adapter, sCopySectStrut.SrcSection, sCopySectStrut.DstSection, sCopySectStrut.offset, sCopySectStrut.numOfBytes); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_GET_FLASH_CS_INFO: { Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \" IOCTL_BCM_GET_FLASH_CS_INFO Called\"); Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Connected device does not have flash\"); Status = -EINVAL; break; } if (IsFlash2x(Adapter) == TRUE) { if (IoBuffer.OutputLength < sizeof(struct bcm_flash2x_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlash2xCSInfo, sizeof(struct bcm_flash2x_cs_info))) return -EFAULT; } else { if (IoBuffer.OutputLength < sizeof(struct bcm_flash_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlashCSInfo, sizeof(struct bcm_flash_cs_info))) return -EFAULT; } } break; case IOCTL_BCM_SELECT_DSD: { UINT SectOfset = 0; enum bcm_flash2x_section_val eFlash2xSectionVal; eFlash2xSectionVal = NO_SECTION_VAL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SELECT_DSD Called\"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of flash section val failed\"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Read Section :%d\", eFlash2xSectionVal); if ((eFlash2xSectionVal != DSD0) && (eFlash2xSectionVal != DSD1) && (eFlash2xSectionVal != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Passed section<%x> is not DSD section\", eFlash2xSectionVal); return STATUS_FAILURE; } SectOfset = BcmGetSectionValStartOffset(Adapter, eFlash2xSectionVal); if (SectOfset == INVALID_OFFSET) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Provided Section val <%d> does not exixt in Flash 2.x\", eFlash2xSectionVal); return -EINVAL; } Adapter->bAllDSDWriteAllow = TRUE; Adapter->ulFlashCalStart = SectOfset; Adapter->eActiveDSD = eFlash2xSectionVal; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_NVM_RAW_READ: { struct bcm_nvm_readwrite stNVMRead; INT NOB ; INT BuffSize ; INT ReadOffset = 0; UINT ReadBytes = 0 ; PUCHAR pReadBuff; void __user *OutPutBuff; if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"NVM TYPE is not Flash\"); return -EINVAL; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"copy_from_user 1 failed\\n\"); return -EFAULT; } if (copy_from_user(&stNVMRead, IoBuffer.OutputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; NOB = stNVMRead.uiNumBytes; \/* In Raw-Read max Buff size : 64MB *\/ if (NOB > DEFAULT_BUFF_SIZE) BuffSize = DEFAULT_BUFF_SIZE; else BuffSize = NOB; ReadOffset = stNVMRead.uiOffset; OutPutBuff = stNVMRead.pBuffer; pReadBuff = kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory allocation failed for Flash 2.x Read Structure\"); Status = -ENOMEM; break; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); kfree(pReadBuff); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Adapter->bFlashRawRead = TRUE; while (NOB) { if (NOB > DEFAULT_BUFF_SIZE) ReadBytes = DEFAULT_BUFF_SIZE; else ReadBytes = NOB; \/* Reading the data from Flash 2.x *\/ Status = BeceemNVMRead(Adapter, (PUINT)pReadBuff, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash 2x read err with Status :%d\", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy to use failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes; } } Adapter->bFlashRawRead = FALSE; up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); break; } case IOCTL_BCM_CNTRLMSG_MASK: { ULONG RxCntrlMsgBitMask = 0; \/* Copy Ioctl Buffer structure *\/ Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"copy of Ioctl buffer is failed from user space\"); return -EFAULT; } if (IoBuffer.InputLength != sizeof(unsigned long)) { Status = -EINVAL; break; } Status = copy_from_user(&RxCntrlMsgBitMask, IoBuffer.InputBuffer, IoBuffer.InputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"copy of control bit mask failed from user space\"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\n Got user defined cntrl msg bit mask :%lx\", RxCntrlMsgBitMask); pTarang->RxCntrlMsgBitMask = RxCntrlMsgBitMask; } break; case IOCTL_BCM_GET_DEVICE_DRIVER_INFO: { struct bcm_driver_info DevInfo; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Called IOCTL_BCM_GET_DEVICE_DRIVER_INFO\\n\"); DevInfo.MaxRDMBufferSize = BUFFER_4K; DevInfo.u32DSDStartOffset = EEPROM_CALPARAM_START; DevInfo.u32RxAlignmentCorrection = 0; DevInfo.u32NVMType = Adapter->eNVMType; DevInfo.u32InterfaceType = BCM_USB; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(DevInfo)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, &DevInfo, sizeof(DevInfo))) return -EFAULT; } break; case IOCTL_BCM_TIME_SINCE_NET_ENTRY: { struct bcm_time_elapsed stTimeElapsedSinceNetEntry = {0}; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_TIME_SINCE_NET_ENTRY called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_time_elapsed)) return -EINVAL; stTimeElapsedSinceNetEntry.ul64TimeElapsedSinceNetEntry = get_seconds() - Adapter->liTimeSinceLastNetEntry; if (copy_to_user(IoBuffer.OutputBuffer, &stTimeElapsedSinceNetEntry, sizeof(struct bcm_time_elapsed))) return -EFAULT; } break; case IOCTL_CLOSE_NOTIFICATION: BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_CLOSE_NOTIFICATION\"); break; default: pr_info(DRV_NAME \": unknown ioctl cmd=%#x\\n\", cmd); Status = STATUS_FAILURE; break; } return Status; }","output":{"is_vulnerable":"True","vulnerability_types":["Exposure of Sensitive Information to an Unauthorized Actor"],"explanation":"The bcm_char_ioctl function in drivers\/staging\/bcm\/Bcmchar.c in the Linux kernel before 3.12 does not initialize a certain data structure, which allows local users to obtain sensitive information from kernel memory via an IOCTL_BCM_GET_DEVICE_DRIVER_INFO ioctl call.","severity_level":"Medium","cwe":"CWE-200","cve":"CVE-2013-4515"}} -{"idx":476012,"input":"void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4496, 3366, 80, 50, 12, 0 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x168, \"EOS 10D\" }, { 0x001, \"EOS-1D\" }, { 0x175, \"EOS 20D\" }, { 0x174, \"EOS-1D Mark II\" }, { 0x234, \"EOS 30D\" }, { 0x232, \"EOS-1D Mark II N\" }, { 0x190, \"EOS 40D\" }, { 0x169, \"EOS-1D Mark III\" }, { 0x261, \"EOS 50D\" }, { 0x281, \"EOS-1D Mark IV\" }, { 0x287, \"EOS 60D\" }, { 0x167, \"EOS-1DS\" }, { 0x170, \"EOS 300D\" }, { 0x188, \"EOS-1Ds Mark II\" }, { 0x176, \"EOS 450D\" }, { 0x215, \"EOS-1Ds Mark III\" }, { 0x189, \"EOS 350D\" }, { 0x324, \"EOS-1D C\" }, { 0x236, \"EOS 400D\" }, { 0x269, \"EOS-1D X\" }, { 0x252, \"EOS 500D\" }, { 0x213, \"EOS 5D\" }, { 0x270, \"EOS 550D\" }, { 0x218, \"EOS 5D Mark II\" }, { 0x286, \"EOS 600D\" }, { 0x285, \"EOS 5D Mark III\" }, { 0x301, \"EOS 650D\" }, { 0x302, \"EOS 6D\" }, { 0x325, \"EOS 70D\" }, { 0x326, \"EOS 700D\" }, { 0x250, \"EOS 7D\" }, { 0x254, \"EOS 1000D\" }, { 0x288, \"EOS 1100D\" }, { 0x346, \"EOS 100D\" }, { 0x331, \"EOS M\" }, }; static const struct { ushort id; char t_model[20]; } sony_unique[] = { {2,\"DSC-R1\"}, {256,\"DSLR-A100\"}, {257,\"DSLR-A900\"}, {258,\"DSLR-A700\"}, {259,\"DSLR-A200\"}, {260,\"DSLR-A350\"}, {261,\"DSLR-A300\"}, {262,\"DSLR-A900\"}, {263,\"DSLR-A380\"}, {264,\"DSLR-A330\"}, {265,\"DSLR-A230\"}, {266,\"DSLR-A290\"}, {269,\"DSLR-A850\"}, {270,\"DSLR-A850\"}, {273,\"DSLR-A550\"}, {274,\"DSLR-A500\"}, {275,\"DSLR-A450\"}, {278,\"NEX-5\"}, {279,\"NEX-3\"}, {280,\"SLT-A33\"}, {281,\"SLT-A55\"}, {282,\"DSLR-A560\"}, {283,\"DSLR-A580\"}, {284,\"NEX-C3\"}, {285,\"SLT-A35\"}, {286,\"SLT-A65\"}, {287,\"SLT-A77\"}, {288,\"NEX-5N\"}, {289,\"NEX-7\"}, {290,\"NEX-VG20E\"}, {291,\"SLT-A37\"}, {292,\"SLT-A57\"}, {293,\"NEX-F3\"}, {294,\"SLT-A99\"}, {295,\"NEX-6\"}, {296,\"NEX-5R\"}, {297,\"DSC-RX100\"}, {298,\"DSC-RX1\"}, {299,\"NEX-VG900\"}, {300,\"NEX-VG30E\"}, {302,\"ILCE-3000\"}, {303,\"SLT-A58\"}, {305,\"NEX-3N\"}, {306,\"ILCE-A7\"}, {307,\"NEX-5T\"}, {308,\"DSC-RX100M2\"}, {310,\"DSC-RX1R\"}, {311,\"ILCE-A7R\"}, }; static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-080C\" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-145C\" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-201C\" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-510C\" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-510C\",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,\"AVT\",\"F-510C\" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,\"AVT\",\"F-510C\",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,\"AVT\",\"F-810C\" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,\"AgfaPhoto\",\"DC-833m\" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,\"Alcatel\",\"5035D\" }, { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,\"Baumer\",\"TXG14\",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,\"Canon\",\"PowerShot SD300\" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,\"Canon\",\"PowerShot A460\" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,\"Canon\",\"PowerShot A610\" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,\"Canon\",\"PowerShot A530\" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,\"Canon\",\"PowerShot S3 IS\" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,\"Canon\",\"PowerShot A620\" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,\"Canon\",\"PowerShot A470\" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,\"Canon\",\"PowerShot A720 IS\" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,\"Canon\",\"PowerShot A630\" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,\"Canon\",\"PowerShot A640\" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,\"Canon\",\"PowerShot A650\" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,\"Canon\",\"PowerShot SX110 IS\" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,\"Canon\",\"PowerShot SX120 IS\" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,\"Canon\",\"PowerShot SX20 IS\" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,\"Canon\",\"PowerShot SX220 HS\" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,\"Canon\",\"PowerShot SX30 IS\" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,\"Canon\",\"PowerShot A3300 IS\" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,\"Casio\",\"QV-2000UX\" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,\"Casio\",\"QV-3*00EX\" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,\"Casio\",\"QV-5700\" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,\"Casio\",\"EX-Z60\" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,\"Casio\",\"EX-S20\" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,\"Casio\",\"EX-S100\" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,\"Casio\",\"QV-R41\" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,\"Casio\",\"EX-P505\" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,\"Casio\",\"QV-R51\" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,\"Casio\",\"EX-Z50\" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,\"Casio\",\"EX-Z500\" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,\"Casio\",\"EX-Z55\" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,\"Casio\",\"EX-P600\" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,\"Casio\",\"EX-Z750\" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,\"Casio\",\"EX-Z75\" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,\"Casio\",\"EX-P700\" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,\"Casio\",\"EX-Z850\" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,\"Casio\",\"EX-Z8\" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,\"Casio\",\"EX-Z1050\" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,\"Casio\",\"EX-ZR100\" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,\"Casio\",\"QV-4000\" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,\"Creative\",\"PC-CAM 600\" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,\"DJI\" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,\"Matrix\" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,\"Foculus\",\"531C\" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,\"Generic\",\"640x480\" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,\"Kodak\",\"DC20\" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,\"Kodak\",\"DC20\" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,\"Kodak\",\"DCS200\" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,\"Kodak\",\"C330\" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,\"Kodak\",\"C330\",3160 }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,\"Kodak\",\"C603\" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,\"Kodak\",\"C603\",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,\"Kodak\",\"C603\" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,\"Kodak\",\"C603\" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,\"Kodak\",\"12MP\" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,\"Kodak\",\"12MP\",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,\"Kodak\",\"12MP\" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,\"Kodak\",\"KAI-0340\" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,\"Micron\",\"2010\",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,\"Minolta\",\"RD175\",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,\"Nikon\",\"E900\" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,\"Nikon\",\"E950\" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,\"Nikon\",\"E2100\" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,\"Nikon\",\"E990\" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,\"Nikon\",\"E3700\" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,\"Nikon\",\"E4500\" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,\"Nikon\",\"E4300\" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,\"Nikon\",\"E5000\" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,\"Nikon\",\"COOLPIX S6\" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,\"Olympus\",\"C770UZ\" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,\"Pentax\",\"Optio S\" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,\"Pentax\",\"Optio S\" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,\"Pentax\",\"Optio S4\" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,\"Pentax\",\"Optio 750Z\" }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,\"Pixelink\",\"A782\" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,\"RoverShot\",\"3320AF\" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,\"ST Micro\",\"STV680 VGA\" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,\"Samsung\",\"S85\" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,\"Samsung\",\"S85\" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,\"Samsung\",\"WB550\" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,\"Samsung\",\"WB550\" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,\"Sinar\",\"3072x2048\",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,\"Sinar\",\"4080x4080\",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,\"Sinar\",\"4080x5440\",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,\"Sony\",\"XCD-SX910CR\" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,\"Sony\",\"XCD-SX910CR\" }, }; static const char *corp[] = { \"AgfaPhoto\", \"Canon\", \"Casio\", \"Epson\", \"Fujifilm\", \"Mamiya\", \"Minolta\", \"Motorola\", \"Kodak\", \"Konica\", \"Leica\", \"Nikon\", \"Nokia\", \"Olympus\", \"Pentax\", \"Phase One\", \"Ricoh\", \"Samsung\", \"Sigma\", \"Sinar\", \"Sony\" }; char head[32], *cp; int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; tiff_flip = flip = filters = UINT_MAX; \/* unknown *\/ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); fread (head, 1, 32, ifp); fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)\"MMMM\", 4)) || (cp = (char *) memmem (head, 32, (char*)\"IIII\", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,\"HEAPCCDR\",8)) { data_offset = hlen; parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,\"\\xff\\xd8\\xff\\xe1\",4) && !memcmp (head+6,\"Exif\",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,\"ARECOYK\",7)) { strcpy (make, \"Contax\"); strcpy (model,\"N Digital\"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 60, SEEK_SET); FORC4 cam_mul[c ^ (c >> 1)] = get4(); } else if (!strcmp (head, \"PXN\")) { strcpy (make, \"Logitech\"); strcpy (model,\"Fotoman Pixtura\"); } else if (!strcmp (head, \"qktk\")) { strcpy (make, \"Apple\"); strcpy (model,\"QuickTake 100\"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, \"qktn\")) { strcpy (make, \"Apple\"); strcpy (model,\"QuickTake 150\"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,\"FUJIFILM\",8)) { fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4()) && 1; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,\"RIFF\",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head,\"\\0\\001\\0\\001\\0@\",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,\"NOKIARAW\",8)) { strcpy (make, \"NOKIA\"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); switch (tiff_bps = i*8 \/ (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i \/ (width * tiff_bps\/8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp (head,\"ARRI\",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, \"ARRI\"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,\"XPDS\",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,\"RED1\",4)) { strcpy (make, \"Red\"); strcpy (model,\"One\"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1\/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,\"DSC-Image\",9)) parse_rollei(); else if (!memcmp (head,\"PWAD\",4)) parse_sinar_ia(); else if (!memcmp (head,\"\\0MRM\",4)) parse_minolta(0); else if (!memcmp (head,\"FOVb\",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!imgdata.params.force_foveon_x3f) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,\"CI\",2)) parse_cine(); else for (zero_fsize=i=0; i < sizeof table \/ sizeof *table; i++) if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 \/ (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); if (!strncmp(model,\"ov\",2) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,\"BRCMn\")) { strcpy (make, \"OmniVision\"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; } else is_raw = 0; } for (i=0; i < sizeof corp \/ sizeof *corp; i++) if (strcasestr (make, corp[i])) \/* Simplify company names *\/ strcpy (make, corp[i]); if ((!strcmp(make,\"Kodak\") || !strcmp(make,\"Leica\")) && ((cp = strcasestr(model,\" DIGITAL CAMERA\")) || (cp = strstr(model,\"FILE VERSION\")))) *cp = 0; if (!strncasecmp(model,\"PENTAX\",6)) strcpy (make, \"Pentax\"); cp = make + strlen(make); \/* Remove trailing spaces *\/ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; i = strlen(make); \/* Remove make from model *\/ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,\"FinePix \",8)) strcpy (model, model+8); if (!strncmp (model,\"Digital Camera \",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) \/* Pentax K10D and Samsung GX10 *\/ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) \/* Pentax K20D and Samsung GX20 *\/ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,\"K-r\") || !strcmp(model,\"K-x\"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,\"K-5\",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 4736 && !strcmp(model,\"K-7\")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,\"K-3\")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,\"645D\")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) \/* Ricoh GX200 *\/ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw = tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: \/* Compression not set, assuming uncompressed *\/ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } goto dng_skip; } if (!strcmp(make,\"Canon\") && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon \/ sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strcmp(make,\"Canon\") && unique_id) { for (i=0; i < sizeof unique \/ sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff (\"Canon\", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strcasecmp(make,\"Sony\") && unique_id) { for (i=0; i < sizeof sony_unique \/ sizeof *sony_unique; i++) if (unique_id == sony_unique[i].id) { adobe_coeff (\"Sony\", sony_unique[i].t_model); strcpy(model,sony_unique[i].t_model); } } if (!strcmp(make,\"Nikon\")) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } \/* Set parameters based on camera name (for non-DNG files). *\/ if (!strcmp(model,\"KAI-0340\") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,\"C603\"); } if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!imgdata.params.force_foveon_x3f) simple_coeff(0); #endif } else if (!strcmp(make,\"Canon\") && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) SWAP(height,width); filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,\"PowerShot 600\")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,\"PowerShot A5\") || !strcmp(model,\"PowerShot A5 Zoom\")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256\/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,\"PowerShot A50\")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,\"PowerShot Pro70\")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,\"PowerShot Pro90 IS\") || !strcmp(model,\"PowerShot G1\")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,\"PowerShot A610\")) { if (canon_s2is()) strcpy (model+10, \"S2 IS\"); } else if (!strcmp(model,\"PowerShot SX220 HS\")) { mask[1][3] = -4; } else if (!strcmp(model,\"EOS D2000C\")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,\"D1\")) { cam_mul[0] *= 256\/527.0; cam_mul[2] *= 256\/317.0; } else if (!strcmp(model,\"D1X\")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,\"D40X\") || !strcmp(model,\"D60\") || !strcmp(model,\"D80\") || !strcmp(model,\"D3000\")) { height -= 3; width -= 4; } else if (!strcmp(model,\"D3\") || !strcmp(model,\"D3S\") || !strcmp(model,\"D700\")) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"D3100\")) { width -= 28; left_margin = 6; } else if (!strcmp(model,\"D5000\") || !strcmp(model,\"D90\")) { width -= 42; } else if (!strcmp(model,\"D5100\") || !strcmp(model,\"D7000\") || !strcmp(model,\"COOLPIX A\")) { width -= 44; } else if (!strcmp(model,\"D3200\") || !strcmp(model,\"D600\") || !strcmp(model,\"D610\") || !strncmp(model,\"D800\",4)) { width -= 46; } else if (!strcmp(model,\"D4\") || !strcmp(model,\"Df\")) { width -= 52; left_margin = 2; } else if (!strncmp(model,\"D40\",3) || !strncmp(model,\"D50\",3) || !strncmp(model,\"D70\",3)) { width--; } else if (!strcmp(model,\"D100\")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,\"D200\")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,\"D2H\",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,\"D2X\",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,\"D300\",4)) { width -= 32; } else if (!strcmp(make,\"Nikon\") && raw_width == 4032) { adobe_coeff (\"Nikon\",\"COOLPIX P7700\"); } else if (!strncmp(model,\"COOLPIX P\",9)) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && iso_speed >= 400) black = 255; } else if (!strncmp(model,\"1 \",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, \"E995\"); if (strcmp(model,\"E995\")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,\"E2500\"); if (!strcmp(model,\"E2500\")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,\"Optio 33WR\")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, \"Minolta\"); strcpy (model,\"DiMAGE Z2\"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, \"ISG\"); model[0] = 0; } } else if (!strcmp(make,\"Fujifilm\")) { if (!strcmp(model+7,\"S2Pro\")) { strcpy (model,\"S2Pro\"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (!strcmp(model,\"HS50EXR\") || !strcmp(model,\"F900EXR\")) { width += 2; left_margin = 0; filters = 0x16161616; } if (fuji_layout) raw_width *= is_raw; } else if (!strcmp(model,\"KD-400Z\")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,\"KD-510Z\")) { goto konica_510z; } else if (!strcasecmp(make,\"Minolta\")) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,\"DiMAGE A\",8)) { if (!strcmp(model,\"DiMAGE A200\")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,\"ALPHA\",5) || !strncmp(model,\"DYNAX\",5) || !strncmp(model,\"MAXXUM\",6)) { sprintf (model+20, \"DYNAX %-10s\", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,\"DiMAGE G\",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,\"*ist D\")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,\"*ist DS\")) { height -= 2; } else if (!strcmp(make,\"Samsung\") && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strcmp(make,\"Samsung\") && raw_height == 3714) { height -= 18; width = 5536; filters = 0x61616161; colors = 3; } else if (!strcmp(make,\"Samsung\") && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strcmp(model,\"EX1\")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,\"WB2000\")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,\"WB550\")) { strcpy (model, \"WB550\"); } else if (!strcmp(model,\"EX2F\")) { height = 3045; width = 4070; top_margin = 3; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,\"STV680 VGA\")) { black = 16; } else if (!strcmp(model,\"N95\")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,\"640x480\")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strcmp(make,\"Hasselblad\")) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; } else if (raw_width == 7410) { height = 5502; width = 7328; top_margin = 4; left_margin = 41; filters = 0x61616161; } else if (raw_width == 9044) { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; } else if (raw_width == 4090) { strcpy (model, \"V96C\"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } } else if (!strcmp(make,\"Sinar\")) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; maximum = 0x3fff; } else if (!strcmp(make,\"Leaf\")) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, \"RBTG\"); strcpy (model, \"CatchLight\"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, \"DCB2\"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, \"Cantare\"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, \"Valeo 6\"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, \"Valeo 6\"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strcmp(make,\"Leica\") || !strcmp(make,\"Panasonic\")) { if ((flen - data_offset) \/ (raw_width*8\/7) == raw_height) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana \/ sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) \"\\x94\\x61\\x49\\x16\" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,\"C770UZ\")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strcmp(make,\"Olympus\")) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,\"E-300\") || !strcmp(model,\"E-500\")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,\"STYLUS1\")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,\"E-330\")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,\"SP550UZ\")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } } else if (!strcmp(model,\"N Digital\")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,\"DSC-F828\")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, \"RGBE\"); } else if (!strcmp(model,\"DSC-V3\")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strcmp(make,\"Sony\") && raw_width == 3984) { adobe_coeff (\"Sony\",\"DSC-R1\"); width = 3925; order = 0x4d4d; } else if (!strcmp(make,\"Sony\") && !strcmp(model,\"ILCE-3000\")) { width -= 32; } else if (!strcmp(make,\"Sony\") && raw_width == 5504) { width -= 8; } else if (!strcmp(make,\"Sony\") && raw_width == 6048) { width -= 24; } else if (!strcmp(make,\"Sony\") && raw_width == 7392) { width -= 24; \/\/ 21 pix really } else if (!strcmp(model,\"DSLR-A100\")) { if (width == 3880) { height--; width = ++raw_width; } else { order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,\"DSLR-A350\")) { height -= 4; } else if (!strcmp(model,\"PIXL\")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,\"C603\") || !strcmp(model,\"C330\") || !strcmp(model,\"12MP\")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : &CLASS kodak_yrgb_load_raw; } else if (!strncasecmp(model,\"EasyShare\",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strcasecmp(make,\"Kodak\")) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,\"NC2000\",6)) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"EOSDCS3B\")) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"EOSDCS1\")) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"DCS420\")) { width -= 4; left_margin = 2; } else if (!strncmp(model,\"DCS460 \",7)) { model[6] = 0; width -= 4; left_margin = 2; } else if (!strcmp(model,\"DCS460A\")) { width -= 4; left_margin = 2; colors = 1; filters = 0; } else if (!strcmp(model,\"DCS660M\")) { black = 214; colors = 1; filters = 0; } else if (!strcmp(model,\"DCS760M\")) { colors = 1; filters = 0; } if (!strcmp(model+4,\"20X\")) strcpy (cdesc, \"MYCY\"); if (strstr(model,\"DC25\")) { strcpy (model, \"DC25\"); data_offset = 15424; } if (!strncmp(model,\"DC2\",3)) { raw_height = 2 + (height = 242); if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) \/ (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) \/ (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,\"40\")) { strcpy (model, \"DC40\"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,\"DC50\")) { strcpy (model, \"DC50\"); height = 512; width = 768; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,\"DC120\")) { strcpy (model, \"DC120\"); height = 976; width = 848; pixel_aspect = height\/0.75\/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,\"DCS200\")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,\"Fotoman Pixtura\")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,\"QuickTake\",9)) { if (head[5]) strcpy (model+10, \"200\"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strcmp(make,\"Rollei\") && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,\"GRAS-50S5C\")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,\"BB-500CL\")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,\"BB-500GE\")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,\"SVS625CL\")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } \/* Early reject for damaged images *\/ if (!load_raw || height < 22 || width < 22 || tiff_bps > 16 || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, \"%dx%d\", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: if ((use_camera_matrix & (use_camera_wb || dng_version)) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff (\"Apple\",\"Quicktake\"); if (fuji_width) { fuji_width = width >> !fuji_layout; if (~fuji_width & 1) filters = 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) maximum = (1 << tiff_bps) - 1; if (!load_raw || height < 22 || width < 22 || tiff_bps > 16 || tiff_samples > 4 || colors > 4) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_(\"%s: You must link dcraw with %s!!\\n\"), ifname, \"libjasper\"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_(\"%s: You must link dcraw with %s!!\\n\"), ifname, \"libjpeg\"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? \"RGBG\":\"GMCY\"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":61224,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MaxTextExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False when converting or mogrifying *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) chunk[i]=(unsigned char) ReadBlobByte(image); p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; \/* Skip nominal layer count, frame count, and play time *\/ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\", \"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, \"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (*p && ((p-chunk) < (ssize_t) length)) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters \", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { \/* Interpolate *\/ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))\/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ else { \/* Interpolate *\/ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":400659,"input":"deliver_message(uschar *id, BOOL forced, BOOL give_up) { int i, rc; int final_yield = DELIVER_ATTEMPTED_NORMAL; time_t now = time(NULL); address_item *addr_last = NULL; uschar *filter_message = NULL; int process_recipients = RECIP_ACCEPT; open_db dbblock; open_db *dbm_file; extern int acl_where; uschar *info = queue_run_pid == (pid_t)0 ? string_sprintf(\"delivering %s\", id) : string_sprintf(\"delivering %s (queue run pid %d)\", id, queue_run_pid); \/* If the D_process_info bit is on, set_process_info() will output debugging information. If not, we want to show this initial information if D_deliver or D_queue_run is set or in verbose mode. *\/ set_process_info(\"%s\", info); if ( !(debug_selector & D_process_info) && (debug_selector & (D_deliver|D_queue_run|D_v)) ) debug_printf(\"%s\\n\", info); \/* Ensure that we catch any subprocesses that are created. Although Exim sets SIG_DFL as its initial default, some routes through the code end up here with it set to SIG_IGN - cases where a non-synchronous delivery process has been forked, but no re-exec has been done. We use sigaction rather than plain signal() on those OS where SA_NOCLDWAIT exists, because we want to be sure it is turned off. (There was a problem on AIX with this.) *\/ #ifdef SA_NOCLDWAIT { struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(SIGCHLD, &act, NULL); } #else signal(SIGCHLD, SIG_DFL); #endif \/* Make the forcing flag available for routers and transports, set up the global message id field, and initialize the count for returned files and the message size. This use of strcpy() is OK because the length id is checked when it is obtained from a command line (the -M or -q options), and otherwise it is known to be a valid message id. *\/ if (id != message_id) Ustrcpy(message_id, id); deliver_force = forced; return_count = 0; message_size = 0; \/* Initialize some flags *\/ update_spool = FALSE; remove_journal = TRUE; \/* Set a known context for any ACLs we call via expansions *\/ acl_where = ACL_WHERE_DELIVERY; \/* Reset the random number generator, so that if several delivery processes are started from a queue runner that has already used random numbers (for sorting), they don't all get the same sequence. *\/ random_seed = 0; \/* Open and lock the message's data file. Exim locks on this one because the header file may get replaced as it is re-written during the delivery process. Any failures cause messages to be written to the log, except for missing files while queue running - another process probably completed delivery. As part of opening the data file, message_subdir gets set. *\/ if ((deliver_datafile = spool_open_datafile(id)) < 0) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ \/* The value of message_size at this point has been set to the data length, plus one for the blank line that notionally precedes the data. *\/ \/* Now read the contents of the header file, which will set up the headers in store, and also the list of recipients and the tree of non-recipients and assorted flags. It updates message_size. If there is a reading or format error, give up; if the message has been around for sufficiently long, remove it. *\/ { uschar * spoolname = string_sprintf(\"%s-H\", id); if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK) { if (errno == ERRNO_SPOOLFORMAT) { struct stat statbuf; if (Ustat(spool_fname(US\"input\", message_subdir, spoolname, US\"\"), &statbuf) == 0) log_write(0, LOG_MAIN, \"Format error in spool file %s: \" \"size=\" OFF_T_FMT, spoolname, statbuf.st_size); else log_write(0, LOG_MAIN, \"Format error in spool file %s\", spoolname); } else log_write(0, LOG_MAIN, \"Error reading spool file %s: %s\", spoolname, strerror(errno)); \/* If we managed to read the envelope data, received_time contains the time the message was received. Otherwise, we can calculate it from the message id. *\/ if (rc != spool_read_hdrerror) { received_time.tv_sec = received_time.tv_usec = 0; \/*XXX subsec precision?*\/ for (i = 0; i < 6; i++) received_time.tv_sec = received_time.tv_sec * BASE_62 + tab62[id[i] - '0']; } \/* If we've had this malformed message too long, sling it. *\/ if (now - received_time.tv_sec > keep_malformed) { Uunlink(spool_fname(US\"msglog\", message_subdir, id, US\"\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-H\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-J\")); log_write(0, LOG_MAIN, \"Message removed because older than %s\", readconf_printtime(keep_malformed)); } (void)close(deliver_datafile); deliver_datafile = -1; return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* The spool header file has been read. Look to see if there is an existing journal file for this message. If there is, it means that a previous delivery attempt crashed (program or host) before it could update the spool header file. Read the list of delivered addresses from the journal and add them to the nonrecipients tree. Then update the spool file. We can leave the journal in existence, as it will get further successful deliveries added to it in this run, and it will be deleted if this function gets to its end successfully. Otherwise it might be needed again. *\/ { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); FILE * jread; if ( (journal_fd = Uopen(fname, O_RDWR|O_APPEND #ifdef O_CLOEXEC | O_CLOEXEC #endif #ifdef O_NOFOLLOW | O_NOFOLLOW #endif , SPOOL_MODE)) >= 0 && lseek(journal_fd, 0, SEEK_SET) == 0 && (jread = fdopen(journal_fd, \"rb\")) ) { while (Ufgets(big_buffer, big_buffer_size, jread)) { int n = Ustrlen(big_buffer); big_buffer[n-1] = 0; tree_add_nonrecipient(big_buffer); DEBUG(D_deliver) debug_printf(\"Previously delivered address %s taken from \" \"journal file\\n\", big_buffer); } rewind(jread); if ((journal_fd = dup(fileno(jread))) < 0) journal_fd = fileno(jread); else (void) fclose(jread); \/* Try to not leak the FILE resource *\/ \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } else if (errno != ENOENT) { log_write(0, LOG_MAIN|LOG_PANIC, \"attempt to open journal for reading gave: \" \"%s\", strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* A null recipients list indicates some kind of disaster. *\/ if (!recipients_list) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN, \"Spool error: no recipients for %s\", fname); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* Handle a message that is frozen. There are a number of different things that can happen, but in the default situation, unless forced, no delivery is attempted. *\/ if (deliver_freeze) { #ifdef SUPPORT_MOVE_FROZEN_MESSAGES \/* Moving to another directory removes the message from Exim's view. Other tools must be used to deal with it. Logging of this action happens in spool_move_message() and its subfunctions. *\/ if ( move_frozen_messages && spool_move_message(id, message_subdir, US\"\", US\"F\") ) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ #endif \/* For all frozen messages (bounces or not), timeout_frozen_after sets the maximum time to keep messages that are frozen. Thaw if we reach it, with a flag causing all recipients to be failed. The time is the age of the message, not the time since freezing. *\/ if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after) { log_write(0, LOG_MAIN, \"cancelled by timeout_frozen_after\"); process_recipients = RECIP_FAIL_TIMEOUT; } \/* For bounce messages (and others with no sender), thaw if the error message ignore timer is exceeded. The message will be discarded if this delivery fails. *\/ else if (!*sender_address && message_age >= ignore_bounce_errors_after) log_write(0, LOG_MAIN, \"Unfrozen by errmsg timer\"); \/* If this is a bounce message, or there's no auto thaw, or we haven't reached the auto thaw time yet, and this delivery is not forced by an admin user, do not attempt delivery of this message. Note that forced is set for continuing messages down the same channel, in order to skip load checking and ignore hold domains, but we don't want unfreezing in that case. *\/ else { if ( ( sender_address[0] == 0 || auto_thaw <= 0 || now <= deliver_frozen_at + auto_thaw ) && ( !forced || !deliver_force_thaw || !admin_user || continue_hostname ) ) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(L_skip_delivery, LOG_MAIN, \"Message is frozen\"); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* If delivery was forced (by an admin user), assume a manual thaw. Otherwise it's an auto thaw. *\/ if (forced) { deliver_manual_thaw = TRUE; log_write(0, LOG_MAIN, \"Unfrozen by forced delivery\"); } else log_write(0, LOG_MAIN, \"Unfrozen by auto-thaw\"); } \/* We get here if any of the rules for unfreezing have triggered. *\/ deliver_freeze = FALSE; update_spool = TRUE; } \/* Open the message log file if we are using them. This records details of deliveries, deferments, and failures for the benefit of the mail administrator. The log is not used by exim itself to track the progress of a message; that is done by rewriting the header spool file. *\/ if (message_logs) { uschar * fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); uschar * error; int fd; if ((fd = open_msglog_file(fname, SPOOL_MODE, &error)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't %s message log %s: %s\", error, fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Make a C stream out of it. *\/ if (!(message_log = fdopen(fd, \"a\"))) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't fdopen message log %s: %s\", fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* If asked to give up on a message, log who did it, and set the action for all the addresses. *\/ if (give_up) { struct passwd *pw = getpwuid(real_uid); log_write(0, LOG_MAIN, \"cancelled by %s\", pw ? US pw->pw_name : string_sprintf(\"uid %ld\", (long int)real_uid)); process_recipients = RECIP_FAIL; } \/* Otherwise, if there are too many Received: headers, fail all recipients. *\/ else if (received_count > received_headers_max) process_recipients = RECIP_FAIL_LOOP; \/* Otherwise, if a system-wide, address-independent message filter is specified, run it now, except in the case when we are failing all recipients as a result of timeout_frozen_after. If the system filter yields \"delivered\", then ignore the true recipients of the message. Failure of the filter file is logged, and the delivery attempt fails. *\/ else if (system_filter && process_recipients != RECIP_FAIL_TIMEOUT) { int rc; int filtertype; ugid_block ugid; redirect_block redirect; if (system_filter_uid_set) { ugid.uid = system_filter_uid; ugid.gid = system_filter_gid; ugid.uid_set = ugid.gid_set = TRUE; } else { ugid.uid_set = ugid.gid_set = FALSE; } return_path = sender_address; enable_dollar_recipients = TRUE; \/* Permit $recipients in system filter *\/ system_filtering = TRUE; \/* Any error in the filter file causes a delivery to be abandoned. *\/ redirect.string = system_filter; redirect.isfile = TRUE; redirect.check_owner = redirect.check_group = FALSE; redirect.owners = NULL; redirect.owngroups = NULL; redirect.pw = NULL; redirect.modemask = 0; DEBUG(D_deliver|D_filter) debug_printf(\"running system filter\\n\"); rc = rda_interpret( &redirect, \/* Where the data is *\/ RDO_DEFER | \/* Turn on all the enabling options *\/ RDO_FAIL | \/* Leave off all the disabling options *\/ RDO_FILTER | RDO_FREEZE | RDO_REALLOG | RDO_REWRITE, NULL, \/* No :include: restriction (not used in filter) *\/ NULL, \/* No sieve vacation directory (not sieve!) *\/ NULL, \/* No sieve enotify mailto owner (not sieve!) *\/ NULL, \/* No sieve user address (not sieve!) *\/ NULL, \/* No sieve subaddress (not sieve!) *\/ &ugid, \/* uid\/gid data *\/ &addr_new, \/* Where to hang generated addresses *\/ &filter_message, \/* Where to put error message *\/ NULL, \/* Don't skip syntax errors *\/ &filtertype, \/* Will always be set to FILTER_EXIM for this call *\/ US\"system filter\"); \/* For error messages *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter returned %d\\n\", rc); if (rc == FF_ERROR || rc == FF_NONEXIST) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN|LOG_PANIC, \"Error in system filter: %s\", string_printing(filter_message)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Reset things. If the filter message is an empty string, which can happen for a filter \"fail\" or \"freeze\" command with no text, reset it to NULL. *\/ system_filtering = FALSE; enable_dollar_recipients = FALSE; if (filter_message && filter_message[0] == 0) filter_message = NULL; \/* Save the values of the system filter variables so that user filters can use them. *\/ memcpy(filter_sn, filter_n, sizeof(filter_sn)); \/* The filter can request that delivery of the original addresses be deferred. *\/ if (rc == FF_DEFER) { process_recipients = RECIP_DEFER; deliver_msglog(\"Delivery deferred by system filter\\n\"); log_write(0, LOG_MAIN, \"Delivery deferred by system filter\"); } \/* The filter can request that a message be frozen, but this does not take place if the message has been manually thawed. In that case, we must unset \"delivered\", which is forced by the \"freeze\" command to make -bF work properly. *\/ else if (rc == FF_FREEZE && !deliver_manual_thaw) { deliver_freeze = TRUE; deliver_frozen_at = time(NULL); process_recipients = RECIP_DEFER; frozen_info = string_sprintf(\" by the system filter%s%s\", filter_message ? US\": \" : US\"\", filter_message ? filter_message : US\"\"); } \/* The filter can request that a message be failed. The error message may be quite long - it is sent back to the sender in the bounce - but we don't want to fill up the log with repetitions of it. If it starts with << then the text between << and >> is written to the log, with the rest left for the bounce message. *\/ else if (rc == FF_FAIL) { uschar *colon = US\"\"; uschar *logmsg = US\"\"; int loglen = 0; process_recipients = RECIP_FAIL_FILTER; if (filter_message) { uschar *logend; colon = US\": \"; if ( filter_message[0] == '<' && filter_message[1] == '<' && (logend = Ustrstr(filter_message, \">>\")) ) { logmsg = filter_message + 2; loglen = logend - logmsg; filter_message = logend + 2; if (filter_message[0] == 0) filter_message = NULL; } else { logmsg = filter_message; loglen = Ustrlen(filter_message); } } log_write(0, LOG_MAIN, \"cancelled by system filter%s%.*s\", colon, loglen, logmsg); } \/* Delivery can be restricted only to those recipients (if any) that the filter specified. *\/ else if (rc == FF_DELIVERED) { process_recipients = RECIP_IGNORE; if (addr_new) log_write(0, LOG_MAIN, \"original recipients ignored (system filter)\"); else log_write(0, LOG_MAIN, \"=> discarded (system filter)\"); } \/* If any new addresses were created by the filter, fake up a \"parent\" for them. This is necessary for pipes, etc., which are expected to have parents, and it also gives some sensible logging for others. Allow pipes, files, and autoreplies, and run them as the filter uid if set, otherwise as the current uid. *\/ if (addr_new) { int uid = (system_filter_uid_set)? system_filter_uid : geteuid(); int gid = (system_filter_gid_set)? system_filter_gid : getegid(); \/* The text \"system-filter\" is tested in transport_set_up_command() and in set_up_shell_command() in the pipe transport, to enable them to permit $recipients, so don't change it here without also changing it there. *\/ address_item *p = addr_new; address_item *parent = deliver_make_addr(US\"system-filter\", FALSE); parent->domain = string_copylc(qualify_domain_recipient); parent->local_part = US\"system-filter\"; \/* As part of this loop, we arrange for addr_last to end up pointing at the final address. This is used if we go on to add addresses for the original recipients. *\/ while (p) { if (parent->child_count == USHRT_MAX) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"system filter generated more \" \"than %d delivery addresses\", USHRT_MAX); parent->child_count++; p->parent = parent; if (testflag(p, af_pfr)) { uschar *tpname; uschar *type; p->uid = uid; p->gid = gid; setflag(p, af_uid_set); setflag(p, af_gid_set); setflag(p, af_allow_file); setflag(p, af_allow_pipe); setflag(p, af_allow_reply); \/* Find the name of the system filter's appropriate pfr transport *\/ if (p->address[0] == '|') { type = US\"pipe\"; tpname = system_filter_pipe_transport; address_pipe = p->address; } else if (p->address[0] == '>') { type = US\"reply\"; tpname = system_filter_reply_transport; } else { if (p->address[Ustrlen(p->address)-1] == '\/') { type = US\"directory\"; tpname = system_filter_directory_transport; } else { type = US\"file\"; tpname = system_filter_file_transport; } address_file = p->address; } \/* Now find the actual transport, first expanding the name. We have set address_file or address_pipe above. *\/ if (tpname) { uschar *tmp = expand_string(tpname); address_file = address_pipe = NULL; if (!tmp) p->message = string_sprintf(\"failed to expand \\\"%s\\\" as a \" \"system filter transport name\", tpname); tpname = tmp; } else p->message = string_sprintf(\"system_filter_%s_transport is unset\", type); if (tpname) { transport_instance *tp; for (tp = transports; tp; tp = tp->next) if (Ustrcmp(tp->name, tpname) == 0) { p->transport = tp; break; } if (!tp) p->message = string_sprintf(\"failed to find \\\"%s\\\" transport \" \"for system filter delivery\", tpname); } \/* If we couldn't set up a transport, defer the delivery, putting the error on the panic log as well as the main log. *\/ if (!p->transport) { address_item *badp = p; p = p->next; if (!addr_last) addr_new = p; else addr_last->next = p; badp->local_part = badp->address; \/* Needed for log line *\/ post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, EXIM_DTYPE_ROUTER, 0); continue; } } \/* End of pfr handling *\/ \/* Either a non-pfr delivery, or we found a transport *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter added %s\\n\", p->address); addr_last = p; p = p->next; } \/* Loop through all addr_new addresses *\/ } } \/* Scan the recipients list, and for every one that is not in the non- recipients tree, add an addr item to the chain of new addresses. If the pno value is non-negative, we must set the onetime parent from it. This which points to the relevant entry in the recipients list. This processing can be altered by the setting of the process_recipients variable, which is changed if recipients are to be ignored, failed, or deferred. This can happen as a result of system filter activity, or if the -Mg option is used to fail all of them. Duplicate addresses are handled later by a different tree structure; we can't just extend the non-recipients tree, because that will be re-written to the spool if the message is deferred, and in any case there are casing complications for local addresses. *\/ if (process_recipients != RECIP_IGNORE) for (i = 0; i < recipients_count; i++) if (!tree_search(tree_nonrecipients, recipients_list[i].address)) { recipient_item *r = recipients_list + i; address_item *new = deliver_make_addr(r->address, FALSE); new->prop.errors_address = r->errors_to; #ifdef SUPPORT_I18N if ((new->prop.utf8_msg = message_smtputf8)) { new->prop.utf8_downcvt = message_utf8_downconvert == 1; new->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1; DEBUG(D_deliver) debug_printf(\"utf8, downconvert %s\\n\", new->prop.utf8_downcvt ? \"yes\" : new->prop.utf8_downcvt_maybe ? \"ifneeded\" : \"no\"); } #endif if (r->pno >= 0) new->onetime_parent = recipients_list[r->pno].address; \/* If DSN support is enabled, set the dsn flags and the original receipt to be passed on to other DSN enabled MTAs *\/ new->dsn_flags = r->dsn_flags & rf_dsnflags; new->dsn_orcpt = r->orcpt; DEBUG(D_deliver) debug_printf(\"DSN: set orcpt: %s flags: %d\\n\", new->dsn_orcpt ? new->dsn_orcpt : US\"\", new->dsn_flags); switch (process_recipients) { \/* RECIP_DEFER is set when a system filter freezes a message. *\/ case RECIP_DEFER: new->next = addr_defer; addr_defer = new; break; \/* RECIP_FAIL_FILTER is set when a system filter has obeyed a \"fail\" command. *\/ case RECIP_FAIL_FILTER: new->message = filter_message ? filter_message : US\"delivery cancelled\"; setflag(new, af_pass_message); goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older than the value in timeout_frozen_after. Treat non-bounce messages similarly to -Mg; for bounce messages we just want to discard, so don't put the address on the failed list. The timeout has already been logged. *\/ case RECIP_FAIL_TIMEOUT: new->message = US\"delivery cancelled; message timed out\"; goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL is set when -Mg has been used. *\/ case RECIP_FAIL: new->message = US\"delivery cancelled by administrator\"; \/* Fall through *\/ \/* Common code for the failure cases above. If this is not a bounce message, put the address on the failed list so that it is used to create a bounce. Otherwise do nothing - this just discards the address. The incident has already been logged. *\/ RECIP_QUEUE_FAILED: if (sender_address[0] != 0) { new->next = addr_failed; addr_failed = new; } break; \/* RECIP_FAIL_LOOP is set when there are too many Received: headers in the message. Process each address as a routing failure; if this is a bounce message, it will get frozen. *\/ case RECIP_FAIL_LOOP: new->message = US\"Too many \\\"Received\\\" headers - suspected mail loop\"; post_process_one(new, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); break; \/* Value should be RECIP_ACCEPT; take this as the safe default. *\/ default: if (!addr_new) addr_new = new; else addr_last->next = new; addr_last = new; break; } #ifndef DISABLE_EVENT if (process_recipients != RECIP_ACCEPT) { uschar * save_local = deliver_localpart; const uschar * save_domain = deliver_domain; uschar * addr = new->address, * errmsg = NULL; int start, end, dom; if (!parse_extract_address(addr, &errmsg, &start, &end, &dom, TRUE)) log_write(0, LOG_MAIN|LOG_PANIC, \"failed to parse address '%.100s': %s\\n\", addr, errmsg); else { deliver_localpart = string_copyn(addr+start, dom ? (dom-1) - start : end - start); deliver_domain = dom ? CUS string_copyn(addr+dom, end - dom) : CUS\"\"; event_raise(event_action, US\"msg:fail:internal\", new->message); deliver_localpart = save_local; deliver_domain = save_domain; } } #endif } DEBUG(D_deliver) { address_item *p; debug_printf(\"Delivery address list:\\n\"); for (p = addr_new; p; p = p->next) debug_printf(\" %s %s\\n\", p->address, p->onetime_parent ? p->onetime_parent : US\"\"); } \/* Set up the buffers used for copying over the file when delivering. *\/ deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE); deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE); \/* Until there are no more new addresses, handle each one as follows: . If this is a generated address (indicated by the presence of a parent pointer) then check to see whether it is a pipe, file, or autoreply, and if so, handle it directly here. The router that produced the address will have set the allow flags into the address, and also set the uid\/gid required. Having the routers generate new addresses and then checking them here at the outer level is tidier than making each router do the checking, and means that routers don't need access to the failed address queue. . Break up the address into local part and domain, and make lowercased versions of these strings. We also make unquoted versions of the local part. . Handle the percent hack for those domains for which it is valid. . For child addresses, determine if any of the parents have the same address. If so, generate a different string for previous delivery checking. Without this code, if the address spqr generates spqr via a forward or alias file, delivery of the generated spqr stops further attempts at the top level spqr, which is not what is wanted - it may have generated other addresses. . Check on the retry database to see if routing was previously deferred, but only if in a queue run. Addresses that are to be routed are put on the addr_route chain. Addresses that are to be deferred are put on the addr_defer chain. We do all the checking first, so as not to keep the retry database open any longer than necessary. . Now we run the addresses through the routers. A router may put the address on either the addr_local or the addr_remote chain for local or remote delivery, respectively, or put it on the addr_failed chain if it is undeliveable, or it may generate child addresses and put them on the addr_new chain, or it may defer an address. All the chain anchors are passed as arguments so that the routers can be called for verification purposes as well. . If new addresses have been generated by the routers, da capo. *\/ header_rewritten = FALSE; \/* No headers rewritten yet *\/ while (addr_new) \/* Loop until all addresses dealt with *\/ { address_item *addr, *parent; \/* Failure to open the retry database is treated the same as if it does not exist. In both cases, dbm_file is NULL. *\/ if (!(dbm_file = dbfn_open(US\"retry\", O_RDONLY, &dbblock, FALSE))) DEBUG(D_deliver|D_retry|D_route|D_hints_lookup) debug_printf(\"no retry data available\\n\"); \/* Scan the current batch of new addresses, to handle pipes, files and autoreplies, and determine which others are ready for routing. *\/ while (addr_new) { int rc; uschar *p; tree_node *tnode; dbdata_retry *domain_retry_record; dbdata_retry *address_retry_record; addr = addr_new; addr_new = addr->next; DEBUG(D_deliver|D_retry|D_route) { debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"Considering: %s\\n\", addr->address); } \/* Handle generated address that is a pipe or a file or an autoreply. *\/ if (testflag(addr, af_pfr)) { \/* If an autoreply in a filter could not generate a syntactically valid address, give up forthwith. Set af_ignore_error so that we don't try to generate a bounce. *\/ if (testflag(addr, af_bad_reply)) { addr->basic_errno = ERRNO_BADADDRESS2; addr->local_part = addr->address; addr->message = US\"filter autoreply generated syntactically invalid recipient\"; addr->prop.ignore_error = TRUE; (void) post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If two different users specify delivery to the same pipe or file or autoreply, there should be two different deliveries, so build a unique string that incorporates the original address, and use this for duplicate testing and recording delivery, and also for retrying. *\/ addr->unique = string_sprintf(\"%s:%s\", addr->address, addr->parent->unique + (testflag(addr->parent, af_homonym)? 3:0)); addr->address_retry_key = addr->domain_retry_key = string_sprintf(\"T:%s\", addr->unique); \/* If a filter file specifies two deliveries to the same pipe or file, we want to de-duplicate, but this is probably not wanted for two mail commands to the same address, where probably both should be delivered. So, we have to invent a different unique string in that case. Just keep piling '>' characters on the front. *\/ if (addr->address[0] == '>') { while (tree_search(tree_duplicates, addr->unique)) addr->unique = string_sprintf(\">%s\", addr->unique); } else if ((tnode = tree_search(tree_duplicates, addr->unique))) { DEBUG(D_deliver|D_route) debug_printf(\"%s is a duplicate address: discarded\\n\", addr->address); addr->dupof = tnode->data.ptr; addr->next = addr_duplicate; addr_duplicate = addr; continue; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); \/* Check for previous delivery *\/ if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->address); child_done(addr, tod_stamp(tod_log)); continue; } \/* Save for checking future duplicates *\/ tree_add_duplicate(addr->unique, addr); \/* Set local part and domain *\/ addr->local_part = addr->address; addr->domain = addr->parent->domain; \/* Ensure that the delivery is permitted. *\/ if (testflag(addr, af_file)) { if (!testflag(addr, af_allow_file)) { addr->basic_errno = ERRNO_FORBIDFILE; addr->message = US\"delivery to file forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (addr->address[0] == '|') { if (!testflag(addr, af_allow_pipe)) { addr->basic_errno = ERRNO_FORBIDPIPE; addr->message = US\"delivery to pipe forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (!testflag(addr, af_allow_reply)) { addr->basic_errno = ERRNO_FORBIDREPLY; addr->message = US\"autoreply forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If the errno field is already set to BADTRANSPORT, it indicates failure to expand a transport string, or find the associated transport, or an unset transport when one is required. Leave this test till now so that the forbid errors are given in preference. *\/ if (addr->basic_errno == ERRNO_BADTRANSPORT) { (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; } \/* Treat \/dev\/null as a special case and abandon the delivery. This avoids having to specify a uid on the transport just for this case. Arrange for the transport name to be logged as \"**bypassed**\". *\/ if (Ustrcmp(addr->address, \"\/dev\/null\") == 0) { uschar *save = addr->transport->name; addr->transport->name = US\"**bypassed**\"; (void)post_process_one(addr, OK, LOG_MAIN, EXIM_DTYPE_TRANSPORT, '='); addr->transport->name = save; continue; \/* with the next new address *\/ } \/* Pipe, file, or autoreply delivery is to go ahead as a normal local delivery. *\/ DEBUG(D_deliver|D_route) debug_printf(\"queued for %s transport\\n\", addr->transport->name); addr->next = addr_local; addr_local = addr; continue; \/* with the next new address *\/ } \/* Handle normal addresses. First, split up into local part and domain, handling the %-hack if necessary. There is the possibility of a defer from a lookup in percent_hack_domains. *\/ if ((rc = deliver_split_address(addr)) == DEFER) { addr->message = US\"cannot check percent_hack_domains\"; addr->basic_errno = ERRNO_LISTDEFER; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Check to see if the domain is held. If so, proceed only if the delivery was forced by hand. *\/ deliver_domain = addr->domain; \/* set $domain *\/ if ( !forced && hold_domains && (rc = match_isinlist(addr->domain, (const uschar **)&hold_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != FAIL ) { if (rc == DEFER) { addr->message = US\"hold_domains lookup deferred\"; addr->basic_errno = ERRNO_LISTDEFER; } else { addr->message = US\"domain is held\"; addr->basic_errno = ERRNO_HELD; } (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Now we can check for duplicates and previously delivered addresses. In order to do this, we have to generate a \"unique\" value for each address, because there may be identical actual addresses in a line of descendents. The \"unique\" field is initialized to the same value as the \"address\" field, but gets changed here to cope with identically-named descendents. *\/ for (parent = addr->parent; parent; parent = parent->parent) if (strcmpic(addr->address, parent->address) == 0) break; \/* If there's an ancestor with the same name, set the homonym flag. This influences how deliveries are recorded. Then add a prefix on the front of the unique address. We use \\n\\ where n starts at 0 and increases each time. It is unlikely to pass 9, but if it does, it may look odd but will still work. This means that siblings or cousins with the same names are treated as duplicates, which is what we want. *\/ if (parent) { setflag(addr, af_homonym); if (parent->unique[0] != '\\\\') addr->unique = string_sprintf(\"\\\\0\\\\%s\", addr->address); else addr->unique = string_sprintf(\"\\\\%c\\\\%s\", parent->unique[1] + 1, addr->address); } \/* Ensure that the domain in the unique field is lower cased, because domains are always handled caselessly. *\/ p = Ustrrchr(addr->unique, '@'); while (*p != 0) { *p = tolower(*p); p++; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->unique); child_done(addr, tod_stamp(tod_log)); continue; } \/* Get the routing retry status, saving the two retry keys (with and without the local part) for subsequent use. If there is no retry record for the standard address routing retry key, we look for the same key with the sender attached, because this form is used by the smtp transport after a 4xx response to RCPT when address_retry_include_sender is true. *\/ addr->domain_retry_key = string_sprintf(\"R:%s\", addr->domain); addr->address_retry_key = string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain); if (dbm_file) { domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key); if ( domain_retry_record && now - domain_retry_record->time_stamp > retry_data_expire ) domain_retry_record = NULL; \/* Ignore if too old *\/ address_retry_record = dbfn_read(dbm_file, addr->address_retry_key); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire ) address_retry_record = NULL; \/* Ignore if too old *\/ if (!address_retry_record) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); address_retry_record = dbfn_read(dbm_file, altkey); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire) address_retry_record = NULL; \/* Ignore if too old *\/ } } else domain_retry_record = address_retry_record = NULL; DEBUG(D_deliver|D_retry) { if (!domain_retry_record) debug_printf(\"no domain retry record\\n\"); if (!address_retry_record) debug_printf(\"no address retry record\\n\"); } \/* If we are sending a message down an existing SMTP connection, we must assume that the message which created the connection managed to route an address to that connection. We do not want to run the risk of taking a long time over routing here, because if we do, the server at the other end of the connection may time it out. This is especially true for messages with lots of addresses. For this kind of delivery, queue_running is not set, so we would normally route all addresses. We take a pragmatic approach and defer routing any addresses that have any kind of domain retry record. That is, we don't even look at their retry times. It doesn't matter if this doesn't work occasionally. This is all just an optimization, after all. The reason for not doing the same for address retries is that they normally arise from 4xx responses, not DNS timeouts. *\/ if (continue_hostname && domain_retry_record) { addr->message = US\"reusing SMTP connection skips previous routing defer\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* If we are in a queue run, defer routing unless there is no retry data or we've passed the next retry time, or this message is forced. In other words, ignore retry data when not in a queue run. However, if the domain retry time has expired, always allow the routing attempt. If it fails again, the address will be failed. This ensures that each address is routed at least once, even after long-term routing failures. If there is an address retry, check that too; just wait for the next retry time. This helps with the case when the temporary error on the address was really message-specific rather than address specific, since it allows other messages through. We also wait for the next retry time if this is a message sent down an existing SMTP connection (even though that will be forced). Otherwise there will be far too many attempts for an address that gets a 4xx error. In fact, after such an error, we should not get here because, the host should not be remembered as one this message needs. However, there was a bug that used to cause this to happen, so it is best to be on the safe side. Even if we haven't reached the retry time in the hints, there is one more check to do, which is for the ultimate address timeout. We only do this check if there is an address retry record and there is not a domain retry record; this implies that previous attempts to handle the address had the retry_use_local_parts option turned on. We use this as an approximation for the destination being like a local delivery, for example delivery over LMTP to an IMAP message store. In this situation users are liable to bump into their quota and thereby have intermittently successful deliveries, which keep the retry record fresh, which can lead to us perpetually deferring messages. *\/ else if ( ( queue_running && !deliver_force || continue_hostname ) && ( ( domain_retry_record && now < domain_retry_record->next_try && !domain_retry_record->expired ) || ( address_retry_record && now < address_retry_record->next_try ) ) && ( domain_retry_record || !address_retry_record || !retry_ultimate_address_timeout(addr->address_retry_key, addr->domain, address_retry_record, now) ) ) { addr->message = US\"retry time not reached\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* The domain is OK for routing. Remember if retry data exists so it can be cleaned up after a successful delivery. *\/ else { if (domain_retry_record || address_retry_record) setflag(addr, af_dr_retry_exists); addr->next = addr_route; addr_route = addr; DEBUG(D_deliver|D_route) debug_printf(\"%s: queued for routing\\n\", addr->address); } } \/* The database is closed while routing is actually happening. Requests to update it are put on a chain and all processed together at the end. *\/ if (dbm_file) dbfn_close(dbm_file); \/* If queue_domains is set, we don't even want to try routing addresses in those domains. During queue runs, queue_domains is forced to be unset. Optimize by skipping this pass through the addresses if nothing is set. *\/ if (!deliver_force && queue_domains) { address_item *okaddr = NULL; while (addr_route) { address_item *addr = addr_route; addr_route = addr->next; deliver_domain = addr->domain; \/* set $domain *\/ if ((rc = match_isinlist(addr->domain, (const uschar **)&queue_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != OK) if (rc == DEFER) { addr->basic_errno = ERRNO_LISTDEFER; addr->message = US\"queue_domains lookup deferred\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } else { addr->next = okaddr; okaddr = addr; } else { addr->basic_errno = ERRNO_QUEUE_DOMAIN; addr->message = US\"domain is in queue_domains\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } } addr_route = okaddr; } \/* Now route those addresses that are not deferred. *\/ while (addr_route) { int rc; address_item *addr = addr_route; const uschar *old_domain = addr->domain; uschar *old_unique = addr->unique; addr_route = addr->next; addr->next = NULL; \/* Just in case some router parameter refers to it. *\/ if (!(return_path = addr->prop.errors_address)) return_path = sender_address; \/* If a router defers an address, add a retry item. Whether or not to use the local part in the key is a property of the router. *\/ if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new, &addr_succeed, v_none)) == DEFER) retry_add_item(addr, addr->router->retry_use_local_part ? string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain) : string_sprintf(\"R:%s\", addr->domain), 0); \/* Otherwise, if there is an existing retry record in the database, add retry items to delete both forms. We must also allow for the possibility of a routing retry that includes the sender address. Since the domain might have been rewritten (expanded to fully qualified) as a result of routing, ensure that the rewritten form is also deleted. *\/ else if (testflag(addr, af_dr_retry_exists)) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); retry_add_item(addr, altkey, rf_delete); retry_add_item(addr, addr->address_retry_key, rf_delete); retry_add_item(addr, addr->domain_retry_key, rf_delete); if (Ustrcmp(addr->domain, old_domain) != 0) retry_add_item(addr, string_sprintf(\"R:%s\", old_domain), rf_delete); } \/* DISCARD is given for :blackhole: and \"seen finish\". The event has been logged, but we need to ensure the address (and maybe parents) is marked done. *\/ if (rc == DISCARD) { address_done(addr, tod_stamp(tod_log)); continue; \/* route next address *\/ } \/* The address is finished with (failed or deferred). *\/ if (rc != OK) { (void)post_process_one(addr, rc, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* route next address *\/ } \/* The address has been routed. If the router changed the domain, it will also have changed the unique address. We have to test whether this address has already been delivered, because it's the unique address that finally gets recorded. *\/ if ( addr->unique != old_unique && tree_search(tree_nonrecipients, addr->unique) != 0 ) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: \" \"discarded\\n\", addr->address); if (addr_remote == addr) addr_remote = addr->next; else if (addr_local == addr) addr_local = addr->next; } \/* If the router has same_domain_copy_routing set, we are permitted to copy the routing for any other addresses with the same domain. This is an optimisation to save repeated DNS lookups for \"standard\" remote domain routing. The option is settable only on routers that generate host lists. We play it very safe, and do the optimization only if the address is routed to a remote transport, there are no header changes, and the domain was not modified by the router. *\/ if ( addr_remote == addr && addr->router->same_domain_copy_routing && !addr->prop.extra_headers && !addr->prop.remove_headers && old_domain == addr->domain ) { address_item **chain = &addr_route; while (*chain) { address_item *addr2 = *chain; if (Ustrcmp(addr2->domain, addr->domain) != 0) { chain = &(addr2->next); continue; } \/* Found a suitable address; take it off the routing list and add it to the remote delivery list. *\/ *chain = addr2->next; addr2->next = addr_remote; addr_remote = addr2; \/* Copy the routing data *\/ addr2->domain = addr->domain; addr2->router = addr->router; addr2->transport = addr->transport; addr2->host_list = addr->host_list; addr2->fallback_hosts = addr->fallback_hosts; addr2->prop.errors_address = addr->prop.errors_address; copyflag(addr2, addr, af_hide_child); copyflag(addr2, addr, af_local_host_removed); DEBUG(D_deliver|D_route) debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\" \"routing %s\\n\" \"Routing for %s copied from %s\\n\", addr2->address, addr2->address, addr->address); } } } \/* Continue with routing the next address. *\/ } \/* Loop to process any child addresses that the routers created, and any rerouted addresses that got put back on the new chain. *\/ \/* Debugging: show the results of the routing *\/ DEBUG(D_deliver|D_retry|D_route) { address_item *p; debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"After routing:\\n Local deliveries:\\n\"); for (p = addr_local; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Remote deliveries:\\n\"); for (p = addr_remote; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Failed addresses:\\n\"); for (p = addr_failed; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Deferred addresses:\\n\"); for (p = addr_defer; p; p = p->next) debug_printf(\" %s\\n\", p->address); } \/* Free any resources that were cached during routing. *\/ search_tidyup(); route_tidyup(); \/* These two variables are set only during routing, after check_local_user. Ensure they are not set in transports. *\/ local_user_gid = (gid_t)(-1); local_user_uid = (uid_t)(-1); \/* Check for any duplicate addresses. This check is delayed until after routing, because the flexibility of the routing configuration means that identical addresses with different parentage may end up being redirected to different addresses. Checking for duplicates too early (as we previously used to) makes this kind of thing not work. *\/ do_duplicate_check(&addr_local); do_duplicate_check(&addr_remote); \/* When acting as an MUA wrapper, we proceed only if all addresses route to a remote transport. The check that they all end up in one transaction happens in the do_remote_deliveries() function. *\/ if ( mua_wrapper && (addr_local || addr_failed || addr_defer) ) { address_item *addr; uschar *which, *colon, *msg; if (addr_local) { addr = addr_local; which = US\"local\"; } else if (addr_defer) { addr = addr_defer; which = US\"deferred\"; } else { addr = addr_failed; which = US\"failed\"; } while (addr->parent) addr = addr->parent; if (addr->message) { colon = US\": \"; msg = addr->message; } else colon = msg = US\"\"; \/* We don't need to log here for a forced failure as it will already have been logged. Defer will also have been logged, but as a defer, so we do need to do the failure logging. *\/ if (addr != addr_failed) log_write(0, LOG_MAIN, \"** %s routing yielded a %s delivery\", addr->address, which); \/* Always write an error to the caller *\/ fprintf(stderr, \"routing %s yielded a %s delivery%s%s\\n\", addr->address, which, colon, msg); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* If this is a run to continue deliveries to an external channel that is already set up, defer any local deliveries. *\/ if (continue_transport) { if (addr_defer) { address_item *addr = addr_defer; while (addr->next) addr = addr->next; addr->next = addr_local; } else addr_defer = addr_local; addr_local = NULL; } \/* Because address rewriting can happen in the routers, we should not really do ANY deliveries until all addresses have been routed, so that all recipients of the message get the same headers. However, this is in practice not always possible, since sometimes remote addresses give DNS timeouts for days on end. The pragmatic approach is to deliver what we can now, saving any rewritten headers so that at least the next lot of recipients benefit from the rewriting that has already been done. If any headers have been rewritten during routing, update the spool file to remember them for all subsequent deliveries. This can be delayed till later if there is only address to be delivered - if it succeeds the spool write need not happen. *\/ if ( header_rewritten && ( addr_local && (addr_local->next || addr_remote) || addr_remote && addr_remote->next ) ) { \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); header_rewritten = FALSE; } \/* If there are any deliveries to be and we do not already have the journal file, create it. This is used to record successful deliveries as soon as possible after each delivery is known to be complete. A file opened with O_APPEND is used so that several processes can run simultaneously. The journal is just insurance against crashes. When the spool file is ultimately updated at the end of processing, the journal is deleted. If a journal is found to exist at the start of delivery, the addresses listed therein are added to the non-recipients. *\/ if (addr_local || addr_remote) { if (journal_fd < 0) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if ((journal_fd = Uopen(fname, #ifdef O_CLOEXEC O_CLOEXEC | #endif O_WRONLY|O_APPEND|O_CREAT|O_EXCL, SPOOL_MODE)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't open journal file %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } \/* Set the close-on-exec flag, make the file owned by Exim, and ensure that the mode is correct - the group setting doesn't always seem to get set automatically. *\/ if( fchown(journal_fd, exim_uid, exim_gid) || fchmod(journal_fd, SPOOL_MODE) #ifndef O_CLOEXEC || fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC) #endif ) { int ret = Uunlink(fname); log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't set perms on journal file %s: %s\", fname, strerror(errno)); if(ret && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } } } else if (journal_fd >= 0) { close(journal_fd); journal_fd = -1; } \/* Now we can get down to the business of actually doing deliveries. Local deliveries are done first, then remote ones. If ever the problems of how to handle fallback transports are figured out, this section can be put into a loop for handling fallbacks, though the uid switching will have to be revised. *\/ \/* Precompile a regex that is used to recognize a parameter in response to an LHLO command, if is isn't already compiled. This may be used on both local and remote LMTP deliveries. *\/ if (!regex_IGNOREQUOTA) regex_IGNOREQUOTA = regex_must_compile(US\"\\\\n250[\\\\s\\\\-]IGNOREQUOTA(\\\\s|\\\\n|$)\", FALSE, TRUE); \/* Handle local deliveries *\/ if (addr_local) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\\n\"); do_local_deliveries(); disable_logging = FALSE; } \/* If queue_run_local is set, we do not want to attempt any remote deliveries, so just queue them all. *\/ if (queue_run_local) while (addr_remote) { address_item *addr = addr_remote; addr_remote = addr->next; addr->next = NULL; addr->basic_errno = ERRNO_LOCAL_ONLY; addr->message = US\"remote deliveries suppressed\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_TRANSPORT, 0); } \/* Handle remote deliveries *\/ if (addr_remote) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\\n\"); \/* Precompile some regex that are used to recognize parameters in response to an EHLO command, if they aren't already compiled. *\/ deliver_init(); \/* Now sort the addresses if required, and do the deliveries. The yield of do_remote_deliveries is FALSE when mua_wrapper is set and all addresses cannot be delivered in one transaction. *\/ if (remote_sort_domains) sort_remote_deliveries(); if (!do_remote_deliveries(FALSE)) { log_write(0, LOG_MAIN, \"** mua_wrapper is set but recipients cannot all \" \"be delivered in one transaction\"); fprintf(stderr, \"delivery to smarthost failed (configuration problem)\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* See if any of the addresses that failed got put on the queue for delivery to their fallback hosts. We do it this way because often the same fallback host is used for many domains, so all can be sent in a single transaction (if appropriately configured). *\/ if (addr_fallback && !mua_wrapper) { DEBUG(D_deliver) debug_printf(\"Delivering to fallback hosts\\n\"); addr_remote = addr_fallback; addr_fallback = NULL; if (remote_sort_domains) sort_remote_deliveries(); do_remote_deliveries(TRUE); } disable_logging = FALSE; } \/* All deliveries are now complete. Ignore SIGTERM during this tidying up phase, to minimize cases of half-done things. *\/ DEBUG(D_deliver) debug_printf(\">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\\n\"); cancel_cutthrough_connection(TRUE, US\"deliveries are done\"); \/* Root privilege is no longer needed *\/ exim_setugid(exim_uid, exim_gid, FALSE, US\"post-delivery tidying\"); set_process_info(\"tidying up after delivering %s\", message_id); signal(SIGTERM, SIG_IGN); \/* When we are acting as an MUA wrapper, the smtp transport will either have succeeded for all addresses, or failed them all in normal cases. However, there are some setup situations (e.g. when a named port does not exist) that cause an immediate exit with deferral of all addresses. Convert those into failures. We do not ever want to retry, nor do we want to send a bounce message. *\/ if (mua_wrapper) { if (addr_defer) { address_item *addr, *nextaddr; for (addr = addr_defer; addr; addr = nextaddr) { log_write(0, LOG_MAIN, \"** %s mua_wrapper forced failure for deferred \" \"delivery\", addr->address); nextaddr = addr->next; addr->next = addr_failed; addr_failed = addr; } addr_defer = NULL; } \/* Now all should either have succeeded or failed. *\/ if (!addr_failed) final_yield = DELIVER_MUA_SUCCEEDED; else { host_item * host; uschar *s = addr_failed->user_message; if (!s) s = addr_failed->message; fprintf(stderr, \"Delivery failed: \"); if (addr_failed->basic_errno > 0) { fprintf(stderr, \"%s\", strerror(addr_failed->basic_errno)); if (s) fprintf(stderr, \": \"); } if ((host = addr_failed->host_used)) fprintf(stderr, \"H=%s [%s]: \", host->name, host->address); if (s) fprintf(stderr, \"%s\", CS s); else if (addr_failed->basic_errno <= 0) fprintf(stderr, \"unknown error\"); fprintf(stderr, \"\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = NULL; } } \/* In a normal configuration, we now update the retry database. This is done in one fell swoop at the end in order not to keep opening and closing (and locking) the database. The code for handling retries is hived off into a separate module for convenience. We pass it the addresses of the various chains, because deferred addresses can get moved onto the failed chain if the retry cutoff time has expired for all alternative destinations. Bypass the updating of the database if the -N flag is set, which is a debugging thing that prevents actual delivery. *\/ else if (!dont_deliver) retry_update(&addr_defer, &addr_failed, &addr_succeed); \/* Send DSN for successful messages if requested *\/ addr_senddsn = NULL; for (addr_dsntmp = addr_succeed; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { \/* af_ignore_error not honored here. it's not an error *\/ DEBUG(D_deliver) debug_printf(\"DSN: processing router : %s\\n\" \"DSN: processing successful delivery address: %s\\n\" \"DSN: Sender_address: %s\\n\" \"DSN: orcpt: %s flags: %d\\n\" \"DSN: envid: %s ret: %d\\n\" \"DSN: Final recipient: %s\\n\" \"DSN: Remote SMTP server supports DSN: %d\\n\", addr_dsntmp->router ? addr_dsntmp->router->name : US\"(unknown)\", addr_dsntmp->address, sender_address, addr_dsntmp->dsn_orcpt ? addr_dsntmp->dsn_orcpt : US\"NULL\", addr_dsntmp->dsn_flags, dsn_envid ? dsn_envid : US\"NULL\", dsn_ret, addr_dsntmp->address, addr_dsntmp->dsn_aware ); \/* send report if next hop not DSN aware or a router flagged \"last DSN hop\" and a report was requested *\/ if ( ( addr_dsntmp->dsn_aware != dsn_support_yes || addr_dsntmp->dsn_flags & rf_dsnlasthop ) && addr_dsntmp->dsn_flags & rf_dsnflags && addr_dsntmp->dsn_flags & rf_notify_success ) { \/* copy and relink address_item and send report with all of them at once later *\/ address_item * addr_next = addr_senddsn; addr_senddsn = store_get(sizeof(address_item)); *addr_senddsn = *addr_dsntmp; addr_senddsn->next = addr_next; } else DEBUG(D_deliver) debug_printf(\"DSN: not sending DSN success message\\n\"); } if (addr_senddsn) { pid_t pid; int fd; \/* create exim process to send message *\/ pid = child_open_exim(&fd); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim returns: %d\\n\", pid); if (pid < 0) \/* Creation of child failed *\/ { log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim failed\\n\"); } else \/* Creation of child succeeded *\/ { FILE *f = fdopen(fd, \"wb\"); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ uschar * bound; transport_ctx tctx = {{0}}; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", sender_address); \/* build unique id for MIME boundary *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); DEBUG(D_deliver) debug_printf(\"DSN: MIME boundary: %s\\n\", bound); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-generated\\n\" \"From: Mail Delivery System \\n\" \"To: %s\\n\" \"Subject: Delivery Status Notification\\n\" \"Content-Type: multipart\/report; report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\\n\" \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\" \"This message was created automatically by mail delivery software.\\n\" \" ----- The following addresses had successful delivery notifications -----\\n\", qualify_domain_sender, sender_address, bound, bound); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) fprintf(f, \"<%s> (relayed %s)\\n\\n\", addr_dsntmp->address, (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? \"via non DSN router\" : addr_dsntmp->dsn_aware == dsn_support_no ? \"to non-DSN-aware mailer\" : \"via non \\\"Remote SMTP\\\" router\" ); fprintf(f, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { if (addr_dsntmp->dsn_orcpt) fprintf(f,\"Original-Recipient: %s\\n\", addr_dsntmp->dsn_orcpt); fprintf(f, \"Action: delivered\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 2.0.0\\n\", addr_dsntmp->address); if (addr_dsntmp->host_used && addr_dsntmp->host_used->name) fprintf(f, \"Remote-MTA: dns; %s\\nDiagnostic-Code: smtp; 250 Ok\\n\\n\", addr_dsntmp->host_used->name); else fprintf(f, \"Diagnostic-Code: X-Exim; relayed via non %s router\\n\\n\", (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? \"DSN\" : \"SMTP\"); } fprintf(f, \"--%s\\nContent-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); fclose(f); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ } } \/* If any addresses failed, we must send a message to somebody, unless af_ignore_error is set, in which case no action is taken. It is possible for several messages to get sent if there are addresses with different requirements. *\/ while (addr_failed) { pid_t pid; int fd; uschar *logtod = tod_stamp(tod_log); address_item *addr; address_item *handled_addr = NULL; address_item **paddr; address_item *msgchain = NULL; address_item **pmsgchain = &msgchain; \/* There are weird cases when logging is disabled in the transport. However, there may not be a transport (address failed by a router). *\/ disable_logging = FALSE; if (addr_failed->transport) disable_logging = addr_failed->transport->disable_logging; DEBUG(D_deliver) debug_printf(\"processing failed address %s\\n\", addr_failed->address); \/* There are only two ways an address in a bounce message can get here: (1) When delivery was initially deferred, but has now timed out (in the call to retry_update() above). We can detect this by testing for af_retry_timedout. If the address does not have its own errors address, we arrange to ignore the error. (2) If delivery failures for bounce messages are being ignored. We can detect this by testing for af_ignore_error. This will also be set if a bounce message has been autothawed and the ignore_bounce_errors_after time has passed. It might also be set if a router was explicitly configured to ignore errors (errors_to = \"\"). If neither of these cases obtains, something has gone wrong. Log the incident, but then ignore the error. *\/ if (sender_address[0] == 0 && !addr_failed->prop.errors_address) { if ( !testflag(addr_failed, af_retry_timedout) && !addr_failed->prop.ignore_error) log_write(0, LOG_MAIN|LOG_PANIC, \"internal error: bounce message \" \"failure is neither frozen nor ignored (it's been ignored)\"); addr_failed->prop.ignore_error = TRUE; } \/* If the first address on the list has af_ignore_error set, just remove it from the list, throw away any saved message file, log it, and mark the recipient done. *\/ if ( addr_failed->prop.ignore_error || ( addr_failed->dsn_flags & rf_dsnflags && (addr_failed->dsn_flags & rf_notify_failure) != rf_notify_failure ) ) { addr = addr_failed; addr_failed = addr->next; if (addr->return_filename) Uunlink(addr->return_filename); log_write(0, LOG_MAIN, \"%s%s%s%s: error ignored\", addr->address, !addr->parent ? US\"\" : US\" <\", !addr->parent ? US\"\" : addr->parent->address, !addr->parent ? US\"\" : US\">\"); address_done(addr, logtod); child_done(addr, logtod); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Otherwise, handle the sending of a message. Find the error address for the first address, then send a message that includes all failed addresses that have the same error address. Note the bounce_recipient is a global so that it can be accessed by $bounce_recipient while creating a customized error message. *\/ else { if (!(bounce_recipient = addr_failed->prop.errors_address)) bounce_recipient = sender_address; \/* Make a subprocess to send a message *\/ if ((pid = child_open_exim(&fd)) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); \/* Creation of child succeeded *\/ else { int ch, rc; int filecount = 0; int rcount = 0; uschar *bcc, *emf_text; FILE *f = fdopen(fd, \"wb\"); FILE *emf = NULL; BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0; int max = (bounce_return_size_limit\/DELIVER_IN_BUFFER_SIZE + 1) * DELIVER_IN_BUFFER_SIZE; uschar * bound; uschar *dsnlimitmsg; uschar *dsnnotifyhdr; int topt; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", bounce_recipient); \/* Scan the addresses for all that have the same errors address, removing them from the addr_failed chain, and putting them on msgchain. *\/ paddr = &addr_failed; for (addr = addr_failed; addr; addr = *paddr) if (Ustrcmp(bounce_recipient, addr->prop.errors_address ? addr->prop.errors_address : sender_address) == 0) { \/* The same - dechain *\/ *paddr = addr->next; *pmsgchain = addr; addr->next = NULL; pmsgchain = &(addr->next); } else paddr = &addr->next; \/* Not the same; skip *\/ \/* Include X-Failed-Recipients: for automatic interpretation, but do not let any one header line get too long. We do this by starting a new header every 50 recipients. Omit any addresses for which the \"hide_child\" flag is set. *\/ for (addr = msgchain; addr; addr = addr->next) { if (testflag(addr, af_hide_child)) continue; if (rcount >= 50) { fprintf(f, \"\\n\"); rcount = 0; } fprintf(f, \"%s%s\", rcount++ == 0 ? \"X-Failed-Recipients: \" : \",\\n \", testflag(addr, af_pfr) && addr->parent ? string_printing(addr->parent->address) : string_printing(addr->address)); } if (rcount > 0) fprintf(f, \"\\n\"); \/* Output the standard headers *\/ if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(f); fprintf(f, \"To: %s\\n\", bounce_recipient); \/* generate boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(f, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); \/* Open a template file if one is provided. Log failure to open, but carry on - default texts will be used. *\/ if (bounce_message_file) if (!(emf = Ufopen(bounce_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for error \" \"message texts: %s\", bounce_message_file, strerror(errno)); \/* Quietly copy to configured additional addresses if required. *\/ if ((bcc = moan_check_errorcopy(bounce_recipient))) fprintf(f, \"Bcc: %s\\n\", bcc); \/* The texts for the message can be read from a template file; if there isn't one, or if it is too short, built-in texts are used. The first emf text is a Subject: and any other headers. *\/ if ((emf_text = next_emf(emf, US\"header\"))) fprintf(f, \"%s\\n\", emf_text); else fprintf(f, \"Subject: Mail delivery failed%s\\n\\n\", to_sender? \": returning message to sender\" : \"\"); \/* output human readable part as text\/plain section *\/ fprintf(f, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((emf_text = next_emf(emf, US\"intro\"))) fprintf(f, \"%s\", CS emf_text); else { fprintf(f, \/* This message has been reworded several times. It seems to be confusing to somebody, however it is worded. I have retreated to the original, simple wording. *\/ \"This message was created automatically by mail delivery software.\\n\"); if (bounce_message_text) fprintf(f, \"%s\", CS bounce_message_text); if (to_sender) fprintf(f, \"\\nA message that you sent could not be delivered to one or more of its\\n\" \"recipients. This is a permanent error. The following address(es) failed:\\n\"); else fprintf(f, \"\\nA message sent by\\n\\n <%s>\\n\\n\" \"could not be delivered to one or more of its recipients. The following\\n\" \"address(es) failed:\\n\", sender_address); } fputc('\\n', f); \/* Process the addresses, leaving them on the msgchain if they have a file name for a return message. (There has already been a check in post_process_one() for the existence of data in the message file.) A TRUE return from print_address_information() means that the address is not hidden. *\/ paddr = &msgchain; for (addr = msgchain; addr; addr = *paddr) { if (print_address_information(addr, f, US\" \", US\"\\n \", US\"\")) print_address_error(addr, f, US\"\"); \/* End the final line for the address *\/ fputc('\\n', f); \/* Leave on msgchain if there's a return file. *\/ if (addr->return_file >= 0) { paddr = &(addr->next); filecount++; } \/* Else save so that we can tick off the recipient when the message is sent. *\/ else { *paddr = addr->next; addr->next = handled_addr; handled_addr = addr; } } fputc('\\n', f); \/* Get the next text, whether we need it or not, so as to be positioned for the one after. *\/ emf_text = next_emf(emf, US\"generated text\"); \/* If there were any file messages passed by the local transports, include them in the message. Then put the address on the handled chain. In the case of a batch of addresses that were all sent to the same transport, the return_file field in all of them will contain the same fd, and the return_filename field in the *last* one will be set (to the name of the file). *\/ if (msgchain) { address_item *nextaddr; if (emf_text) fprintf(f, \"%s\", CS emf_text); else fprintf(f, \"The following text was generated during the delivery \" \"attempt%s:\\n\", (filecount > 1)? \"s\" : \"\"); for (addr = msgchain; addr; addr = nextaddr) { FILE *fm; address_item *topaddr = addr; \/* List all the addresses that relate to this file *\/ fputc('\\n', f); while(addr) \/* Insurance *\/ { print_address_information(addr, f, US\"------ \", US\"\\n \", US\" ------\\n\"); if (addr->return_filename) break; addr = addr->next; } fputc('\\n', f); \/* Now copy the file *\/ if (!(fm = Ufopen(addr->return_filename, \"rb\"))) fprintf(f, \" +++ Exim error... failed to open text file: %s\\n\", strerror(errno)); else { while ((ch = fgetc(fm)) != EOF) fputc(ch, f); (void)fclose(fm); } Uunlink(addr->return_filename); \/* Can now add to handled chain, first fishing off the next address on the msgchain. *\/ nextaddr = addr->next; addr->next = handled_addr; handled_addr = topaddr; } fputc('\\n', f); } \/* output machine readable part *\/ #ifdef SUPPORT_I18N if (message_smtputf8) fprintf(f, \"--%s\\n\" \"Content-type: message\/global-delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); else #endif fprintf(f, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for (addr = handled_addr; addr; addr = addr->next) { host_item * hu; fprintf(f, \"Action: failed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 5.0.0\\n\", addr->address); if ((hu = addr->host_used) && hu->name) { const uschar * s; fprintf(f, \"Remote-MTA: dns; %s\\n\", hu->name); #ifdef EXPERIMENTAL_DSN_INFO if (hu->address) { uschar * p = hu->port == 25 ? US\"\" : string_sprintf(\":%d\", hu->port); fprintf(f, \"Remote-MTA: X-ip; [%s]%s\\n\", hu->address, p); } if ((s = addr->smtp_greeting) && *s) fprintf(f, \"X-Remote-MTA-smtp-greeting: X-str; %s\\n\", s); if ((s = addr->helo_response) && *s) fprintf(f, \"X-Remote-MTA-helo-response: X-str; %s\\n\", s); if ((s = addr->message) && *s) fprintf(f, \"X-Exim-Diagnostic: X-str; %s\\n\", s); #endif print_dsn_diagnostic_code(addr, f); } fputc('\\n', f); } \/* Now copy the message, trying to give an intelligible comment if it is too long for it all to be copied. The limit isn't strictly applied because of the buffering. There is, however, an option to suppress copying altogether. *\/ emf_text = next_emf(emf, US\"copy\"); \/* add message body we ignore the intro text from template and add the text for bounce_return_size_limit at the end. bounce_return_message is ignored in case RET= is defined we honor these values otherwise bounce_return_body is honored. bounce_return_size_limit is always honored. *\/ fprintf(f, \"--%s\\n\", bound); dsnlimitmsg = US\"X-Exim-DSN-Information: Due to administrative limits only headers are returned\"; dsnnotifyhdr = NULL; topt = topt_add_return_path; \/* RET=HDRS? top priority *\/ if (dsn_ret == dsn_ret_hdrs) topt |= topt_no_body; else { struct stat statbuf; \/* no full body return at all? *\/ if (!bounce_return_body) { topt |= topt_no_body; \/* add header if we overrule RET=FULL *\/ if (dsn_ret == dsn_ret_full) dsnnotifyhdr = dsnlimitmsg; } \/* line length limited... return headers only if oversize *\/ \/* size limited ... return headers only if limit reached *\/ else if ( max_received_linelength > bounce_return_linesize_limit || ( bounce_return_size_limit > 0 && fstat(deliver_datafile, &statbuf) == 0 && statbuf.st_size > max ) ) { topt |= topt_no_body; dsnnotifyhdr = dsnlimitmsg; } } #ifdef SUPPORT_I18N if (message_smtputf8) fputs(topt & topt_no_body ? \"Content-type: message\/global-headers\\n\\n\" : \"Content-type: message\/global\\n\\n\", f); else #endif fputs(topt & topt_no_body ? \"Content-type: text\/rfc822-headers\\n\\n\" : \"Content-type: message\/rfc822\\n\\n\", f); fflush(f); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ { \/* Dummy transport for headers add *\/ transport_ctx tctx = {{0}}; transport_instance tb = {0}; tctx.u.fd = fileno(f); tctx.tblock = &tb; tctx.options = topt; tb.add_headers = dsnnotifyhdr; transport_write_message(&tctx, 0); } fflush(f); \/* we never add the final text. close the file *\/ if (emf) (void)fclose(emf); fprintf(f, \"\\n--%s--\\n\", bound); \/* Close the file, which should send an EOF to the child process that is receiving the message. Wait for it to finish. *\/ (void)fclose(f); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ \/* In the test harness, let the child do it's thing first. *\/ if (running_in_test_harness) millisleep(500); \/* If the process failed, there was some disaster in setting up the error message. Unless the message is very old, ensure that addr_defer is non-null, which will have the effect of leaving the message on the spool. The failed addresses will get tried again next time. However, we don't really want this to happen too often, so freeze the message unless there are some genuine deferred addresses to try. To do this we have to call spool_write_header() here, because with no genuine deferred addresses the normal code below doesn't get run. *\/ if (rc != 0) { uschar *s = US\"\"; if (now - received_time.tv_sec < retry_maximum_timeout && !addr_defer) { addr_defer = (address_item *)(+1); deliver_freeze = TRUE; deliver_frozen_at = time(NULL); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); s = US\" (frozen)\"; } deliver_msglog(\"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); log_write(0, LOG_MAIN, \"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); } \/* The message succeeded. Ensure that the recipients that failed are now marked finished with on the spool and their parents updated. *\/ else { for (addr = handled_addr; addr; addr = addr->next) { address_done(addr, logtod); child_done(addr, logtod); } \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } } } } disable_logging = FALSE; \/* In case left set *\/ \/* Come here from the mua_wrapper case if routing goes wrong *\/ DELIVERY_TIDYUP: \/* If there are now no deferred addresses, we are done. Preserve the message log if so configured, and we are using them. Otherwise, sling it. Then delete the message itself. *\/ if (!addr_defer) { uschar * fname; if (message_logs) { fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); if (preserve_message_logs) { int rc; uschar * moname = spool_fname(US\"msglog.OLD\", US\"\", id, US\"\"); if ((rc = Urename(fname, moname)) < 0) { (void)directory_make(spool_directory, spool_sname(US\"msglog.OLD\", US\"\"), MSGLOG_DIRECTORY_MODE, TRUE); rc = Urename(fname, moname); } if (rc < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to move %s to the \" \"msglog.OLD directory\", fname); } else if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); } \/* Remove the two message files. *\/ fname = spool_fname(US\"input\", message_subdir, id, US\"-D\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); fname = spool_fname(US\"input\", message_subdir, id, US\"-H\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Log the end of this message, with queue time if requested. *\/ if (LOGGING(queue_time_overall)) log_write(0, LOG_MAIN, \"Completed QT=%s\", string_timesince(&received_time)); else log_write(0, LOG_MAIN, \"Completed\"); \/* Unset deliver_freeze so that we won't try to move the spool files further down *\/ deliver_freeze = FALSE; #ifndef DISABLE_EVENT (void) event_raise(event_action, US\"msg:complete\", NULL); #endif } \/* If there are deferred addresses, we are keeping this message because it is not yet completed. Lose any temporary files that were catching output from pipes for any of the deferred addresses, handle one-time aliases, and see if the message has been on the queue for so long that it is time to send a warning message to the sender, unless it is a mailer-daemon. If all deferred addresses have the same domain, we can set deliver_domain for the expansion of delay_warning_ condition - if any of them are pipes, files, or autoreplies, use the parent's domain. If all the deferred addresses have an error number that indicates \"retry time not reached\", skip sending the warning message, because it won't contain the reason for the delay. It will get sent at the next real delivery attempt. However, if at least one address has tried, we'd better include all of them in the message. If we can't make a process to send the message, don't worry. For mailing list expansions we want to send the warning message to the mailing list manager. We can't do a perfect job here, as some addresses may have different errors addresses, but if we take the errors address from each deferred address it will probably be right in most cases. If addr_defer == +1, it means there was a problem sending an error message for failed addresses, and there were no \"real\" deferred addresses. The value was set just to keep the message on the spool, so there is nothing to do here. *\/ else if (addr_defer != (address_item *)(+1)) { address_item *addr; uschar *recipients = US\"\"; BOOL delivery_attempted = FALSE; deliver_domain = testflag(addr_defer, af_pfr) ? addr_defer->parent->domain : addr_defer->domain; for (addr = addr_defer; addr; addr = addr->next) { address_item *otaddr; if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE; if (deliver_domain) { const uschar *d = testflag(addr, af_pfr) ? addr->parent->domain : addr->domain; \/* The domain may be unset for an address that has never been routed because the system filter froze the message. *\/ if (!d || Ustrcmp(d, deliver_domain) != 0) deliver_domain = NULL; } if (addr->return_filename) Uunlink(addr->return_filename); \/* Handle the case of one-time aliases. If any address in the ancestry of this one is flagged, ensure it is in the recipients list, suitably flagged, and that its parent is marked delivered. *\/ for (otaddr = addr; otaddr; otaddr = otaddr->parent) if (otaddr->onetime_parent) break; if (otaddr) { int i; int t = recipients_count; for (i = 0; i < recipients_count; i++) { uschar *r = recipients_list[i].address; if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i; if (Ustrcmp(otaddr->address, r) == 0) break; } \/* Didn't find the address already in the list, and did find the ultimate parent's address in the list, and they really are different (i.e. not from an identity-redirect). After adding the recipient, update the errors address in the recipients list. *\/ if ( i >= recipients_count && t < recipients_count && Ustrcmp(otaddr->address, otaddr->parent->address) != 0) { DEBUG(D_deliver) debug_printf(\"one_time: adding %s in place of %s\\n\", otaddr->address, otaddr->parent->address); receive_add_recipient(otaddr->address, t); recipients_list[recipients_count-1].errors_to = otaddr->prop.errors_address; tree_add_nonrecipient(otaddr->parent->address); update_spool = TRUE; } } \/* Except for error messages, ensure that either the errors address for this deferred address or, if there is none, the sender address, is on the list of recipients for a warning message. *\/ if (sender_address[0]) { uschar * s = addr->prop.errors_address; if (!s) s = sender_address; if (Ustrstr(recipients, s) == NULL) recipients = string_sprintf(\"%s%s%s\", recipients, recipients[0] ? \",\" : \"\", s); } } \/* Send a warning message if the conditions are right. If the condition check fails because of a lookup defer, there is nothing we can do. The warning is not sent. Another attempt will be made at the next delivery attempt (if it also defers). *\/ if ( !queue_2stage && delivery_attempted && ( ((addr_defer->dsn_flags & rf_dsnflags) == 0) || (addr_defer->dsn_flags & rf_notify_delay) == rf_notify_delay ) && delay_warning[1] > 0 && sender_address[0] != 0 && ( !delay_warning_condition || expand_check_condition(delay_warning_condition, US\"delay_warning\", US\"option\") ) ) { int count; int show_time; int queue_time = time(NULL) - received_time.tv_sec; \/* When running in the test harness, there's an option that allows us to fudge this time so as to get repeatability of the tests. Take the first time off the list. In queue runs, the list pointer gets updated in the calling process. *\/ if (running_in_test_harness && fudged_queue_times[0] != 0) { int qt = readconf_readtime(fudged_queue_times, '\/', FALSE); if (qt >= 0) { DEBUG(D_deliver) debug_printf(\"fudged queue_times = %s\\n\", fudged_queue_times); queue_time = qt; } } \/* See how many warnings we should have sent by now *\/ for (count = 0; count < delay_warning[1]; count++) if (queue_time < delay_warning[count+2]) break; show_time = delay_warning[count+1]; if (count >= delay_warning[1]) { int extra; int last_gap = show_time; if (count > 1) last_gap -= delay_warning[count]; extra = (queue_time - delay_warning[count+1])\/last_gap; show_time += last_gap * extra; count += extra; } DEBUG(D_deliver) { debug_printf(\"time on queue = %s\\n\", readconf_printtime(queue_time)); debug_printf(\"warning counts: required %d done %d\\n\", count, warning_count); } \/* We have computed the number of warnings there should have been by now. If there haven't been enough, send one, and up the count to what it should have been. *\/ if (warning_count < count) { header_line *h; int fd; pid_t pid = child_open_exim(&fd); if (pid > 0) { uschar *wmf_text; FILE *wmf = NULL; FILE *f = fdopen(fd, \"wb\"); uschar * bound; transport_ctx tctx = {{0}}; if (warn_message_file) if (!(wmf = Ufopen(warn_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for warning \" \"message texts: %s\", warn_message_file, strerror(errno)); warnmsg_recipients = recipients; warnmsg_delay = queue_time < 120*60 ? string_sprintf(\"%d minutes\", show_time\/60) : string_sprintf(\"%d hours\", show_time\/3600); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(f); fprintf(f, \"To: %s\\n\", recipients); \/* generated boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(f, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); if ((wmf_text = next_emf(wmf, US\"header\"))) fprintf(f, \"%s\\n\", wmf_text); else fprintf(f, \"Subject: Warning: message %s delayed %s\\n\\n\", message_id, warnmsg_delay); \/* output human readable part as text\/plain section *\/ fprintf(f, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((wmf_text = next_emf(wmf, US\"intro\"))) fprintf(f, \"%s\", CS wmf_text); else { fprintf(f, \"This message was created automatically by mail delivery software.\\n\"); if (Ustrcmp(recipients, sender_address) == 0) fprintf(f, \"A message that you sent has not yet been delivered to one or more of its\\n\" \"recipients after more than \"); else fprintf(f, \"A message sent by\\n\\n <%s>\\n\\n\" \"has not yet been delivered to one or more of its recipients after more than \\n\", sender_address); fprintf(f, \"%s on the queue on %s.\\n\\n\" \"The message identifier is: %s\\n\", warnmsg_delay, primary_hostname, message_id); for (h = header_list; h; h = h->next) if (strncmpic(h->text, US\"Subject:\", 8) == 0) fprintf(f, \"The subject of the message is: %s\", h->text + 9); else if (strncmpic(h->text, US\"Date:\", 5) == 0) fprintf(f, \"The date of the message is: %s\", h->text + 6); fputc('\\n', f); fprintf(f, \"The address%s to which the message has not yet been \" \"delivered %s:\\n\", !addr_defer->next ? \"\" : \"es\", !addr_defer->next ? \"is\": \"are\"); } \/* List the addresses, with error information if allowed *\/ \/* store addr_defer for machine readable part *\/ address_item *addr_dsndefer = addr_defer; fputc('\\n', f); while (addr_defer) { address_item *addr = addr_defer; addr_defer = addr->next; if (print_address_information(addr, f, US\" \", US\"\\n \", US\"\")) print_address_error(addr, f, US\"Delay reason: \"); fputc('\\n', f); } fputc('\\n', f); \/* Final text *\/ if (wmf) { if ((wmf_text = next_emf(wmf, US\"final\"))) fprintf(f, \"%s\", CS wmf_text); (void)fclose(wmf); } else { fprintf(f, \"No action is required on your part. Delivery attempts will continue for\\n\" \"some time, and this warning may be repeated at intervals if the message\\n\" \"remains undelivered. Eventually the mail delivery software will give up,\\n\" \"and when that happens, the message will be returned to you.\\n\"); } \/* output machine readable part *\/ fprintf(f, \"\\n--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f,\"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f,\"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for ( ; addr_dsndefer; addr_dsndefer = addr_dsndefer->next) { if (addr_dsndefer->dsn_orcpt) fprintf(f, \"Original-Recipient: %s\\n\", addr_dsndefer->dsn_orcpt); fprintf(f, \"Action: delayed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 4.0.0\\n\", addr_dsndefer->address); if (addr_dsndefer->host_used && addr_dsndefer->host_used->name) { fprintf(f, \"Remote-MTA: dns; %s\\n\", addr_dsndefer->host_used->name); print_dsn_diagnostic_code(addr_dsndefer, f); } fputc('\\n', f); } fprintf(f, \"--%s\\n\" \"Content-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); \/* Close and wait for child process to complete, without a timeout. If there's an error, don't update the count. *\/ (void)fclose(f); if (child_close(pid, 0) == 0) { warning_count = count; update_spool = TRUE; \/* Ensure spool rewritten *\/ } } } } \/* Clear deliver_domain *\/ deliver_domain = NULL; \/* If this was a first delivery attempt, unset the first time flag, and ensure that the spool gets updated. *\/ if (deliver_firsttime) { deliver_firsttime = FALSE; update_spool = TRUE; } \/* If delivery was frozen and freeze_tell is set, generate an appropriate message, unless the message is a local error message (to avoid loops). Then log the freezing. If the text in \"frozen_info\" came from a system filter, it has been escaped into printing characters so as not to mess up log lines. For the \"tell\" message, we turn \\n back into newline. Also, insert a newline near the start instead of the \": \" string. *\/ if (deliver_freeze) { if (freeze_tell && freeze_tell[0] != 0 && !local_error_message) { uschar *s = string_copy(frozen_info); uschar *ss = Ustrstr(s, \" by the system filter: \"); if (ss != NULL) { ss[21] = '.'; ss[22] = '\\n'; } ss = s; while (*ss != 0) { if (*ss == '\\\\' && ss[1] == 'n') { *ss++ = ' '; *ss++ = '\\n'; } else ss++; } moan_tell_someone(freeze_tell, addr_defer, US\"Message frozen\", \"Message %s has been frozen%s.\\nThe sender is <%s>.\\n\", message_id, s, sender_address); } \/* Log freezing just before we update the -H file, to minimize the chance of a race problem. *\/ deliver_msglog(\"*** Frozen%s\\n\", frozen_info); log_write(0, LOG_MAIN, \"Frozen%s\", frozen_info); } \/* If there have been any updates to the non-recipients list, or other things that get written to the spool, we must now update the spool header file so that it has the right information for the next delivery attempt. If there was more than one address being delivered, the header_change update is done earlier, in case one succeeds and then something crashes. *\/ DEBUG(D_deliver) debug_printf(\"delivery deferred: update_spool=%d header_rewritten=%d\\n\", update_spool, header_rewritten); if (update_spool || header_rewritten) \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Finished with the message log. If the message is complete, it will have been unlinked or renamed above. *\/ if (message_logs) (void)fclose(message_log); \/* Now we can close and remove the journal file. Its only purpose is to record successfully completed deliveries asap so that this information doesn't get lost if Exim (or the machine) crashes. Forgetting about a failed delivery is not serious, as trying it again is not harmful. The journal might not be open if all addresses were deferred at routing or directing. Nevertheless, we must remove it if it exists (may have been lying around from a crash during the previous delivery attempt). We don't remove the journal if a delivery subprocess failed to pass back delivery information; this is controlled by the remove_journal flag. When the journal is left, we also don't move the message off the main spool if frozen and the option is set. It should get moved at the next attempt, after the journal has been inspected. *\/ if (journal_fd >= 0) (void)close(journal_fd); if (remove_journal) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if (Uunlink(fname) < 0 && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Move the message off the spool if requested *\/ #ifdef SUPPORT_MOVE_FROZEN_MESSAGES if (deliver_freeze && move_frozen_messages) (void)spool_move_message(id, message_subdir, US\"\", US\"F\"); #endif } \/* Closing the data file frees the lock; if the file has been unlinked it will go away. Otherwise the message becomes available for another process to try delivery. *\/ (void)close(deliver_datafile); deliver_datafile = -1; DEBUG(D_deliver) debug_printf(\"end delivery of %s\\n\", id); \/* It is unlikely that there will be any cached resources, since they are released after routing, and in the delivery subprocesses. However, it's possible for an expansion for something afterwards (for example, expand_check_condition) to do a lookup. We must therefore be sure everything is released. *\/ search_tidyup(); acl_where = ACL_WHERE_UNKNOWN; return final_yield; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":71941,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if ((length > PNG_UINT_31_MAX) || (length > GetBlobSize(image)) || (count < 4)) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 9) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id >= MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS-1; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { \/* Read global PLTE. *\/ if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (((p-chunk) < (long) length) && *p) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || (length % 2) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { if (loop_iters > GetMagickResourceLimit(ListLengthResource)) loop_iters=GetMagickResourceLimit(ListLengthResource); if (loop_iters >= 2147483647L) loop_iters=2147483647L; mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { if (prev != (Quantum *) NULL) prev=(Quantum *) RelinquishMagickMemory(prev); if (next != (Quantum *) NULL) next=(Quantum *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (Quantum *) NULL) break; q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":507485,"input":"void round_corners(GVJ_t * job, pointf * AF, int sides, int style, int filled) { pointf *B, C[5], *D, p0, p1; double rbconst, d, dx, dy, t; int i, seg, mode, shape; pointf* pts; shape = style & SHAPE_MASK; if (style & DIAGONALS) mode = DIAGONALS; else if (style & SHAPE_MASK) mode = shape; else mode = ROUNDED; if (mode == CYLINDER) { cylinder_draw (job, AF, sides, style, filled); return; } B = N_NEW(4 * sides + 4, pointf); i = 0; \/* rbconst is distance offset from a corner of the polygon. * It should be the same for every corner, and also never * bigger than one-third the length of a side. *\/ rbconst = RBCONST; for (seg = 0; seg < sides; seg++) { p0 = AF[seg]; if (seg < sides - 1) p1 = AF[seg + 1]; else p1 = AF[0]; dx = p1.x - p0.x; dy = p1.y - p0.y; d = sqrt(dx * dx + dy * dy); rbconst = MIN(rbconst, d \/ 3.0); } for (seg = 0; seg < sides; seg++) { p0 = AF[seg]; if (seg < sides - 1) p1 = AF[seg + 1]; else p1 = AF[0]; dx = p1.x - p0.x; dy = p1.y - p0.y; d = sqrt(dx * dx + dy * dy); t = rbconst \/ d; if (shape == BOX3D || shape == COMPONENT) t \/= 3; else if (shape == DOGEAR) t \/= 2; if (mode != ROUNDED) B[i++] = p0; else B[i++] = interpolate_pointf(RBCURVE * t, p0, p1); B[i++] = interpolate_pointf(t, p0, p1); B[i++] = interpolate_pointf(1.0 - t, p0, p1); if (mode == ROUNDED) B[i++] = interpolate_pointf(1.0 - RBCURVE * t, p0, p1); } B[i++] = B[0]; B[i++] = B[1]; B[i++] = B[2]; switch (mode) { case ROUNDED: pts = N_GNEW(6 * sides + 2, pointf); i = 0; for (seg = 0; seg < sides; seg++) { pts[i++] = B[4 * seg]; pts[i++] = B[4 * seg+1]; pts[i++] = B[4 * seg+1]; pts[i++] = B[4 * seg+2]; pts[i++] = B[4 * seg+2]; pts[i++] = B[4 * seg+3]; } pts[i++] = pts[0]; pts[i++] = pts[1]; gvrender_beziercurve(job, pts+1, i-1, FALSE, FALSE, filled); free (pts); #if 0 if (filled) { pointf *pts = N_GNEW(2 * sides, pointf); pts[j++] = B[4 * seg + 1]; pts[j++] = B[4 * seg + 2]; } gvrender_polygon(job, pts, 2 * sides, filled); free(pts); for (seg = 0; seg < sides; seg++) { } } if (penc) { for (seg = 0; seg < sides; seg++) { gvrender_polyline(job, B + 4 * seg + 1, 2); gvrender_beziercurve(job, B + 4 * seg + 2, 4, FALSE, FALSE, FALSE); } } #endif break; case DIAGONALS: \/* diagonals are weird. rewrite someday. *\/ gvrender_polygon(job, AF, sides, filled); for (seg = 0; seg < sides; seg++) { #ifdef NOTDEF C[0] = B[3 * seg]; C[1] = B[3 * seg + 3]; gvrender_polyline(job, C, 2); #endif C[0] = B[3 * seg + 2]; C[1] = B[3 * seg + 4]; gvrender_polyline(job, C, 2); } break; case DOGEAR: \/* Add the cutoff edge. *\/ D = N_NEW(sides + 1, pointf); for (seg = 1; seg < sides; seg++) D[seg] = AF[seg]; D[0] = B[3 * (sides - 1) + 4]; D[sides] = B[3 * (sides - 1) + 2]; gvrender_polygon(job, D, sides + 1, filled); free(D); \/* Draw the inner edge. *\/ seg = sides - 1; C[0] = B[3 * seg + 2]; C[1] = B[3 * seg + 4]; C[2].x = C[1].x + (C[0].x - B[3 * seg + 3].x); C[2].y = C[1].y + (C[0].y - B[3 * seg + 3].y); gvrender_polyline(job, C + 1, 2); C[1] = C[2]; gvrender_polyline(job, C, 2); break; case TAB: \/* * Adjust the perimeter for the protrusions. * * D[3] +--+ D[2] * | | B[1] * B[3] + +----------+--+ AF[0]=B[0]=D[0] * | B[2]=D[1] | * B[4] + | * | | * B[5] + | * +----------------+ * *\/ \/* Add the tab edges. *\/ D = N_NEW(sides + 2, pointf); D[0] = AF[0]; D[1] = B[2]; D[2].x = B[2].x + (B[3].x - B[4].x) \/ 3; D[2].y = B[2].y + (B[3].y - B[4].y) \/ 3; D[3].x = B[3].x + (B[3].x - B[4].x) \/ 3; D[3].y = B[3].y + (B[3].y - B[4].y) \/ 3; for (seg = 4; seg < sides + 2; seg++) D[seg] = AF[seg - 2]; gvrender_polygon(job, D, sides + 2, filled); free(D); \/* Draw the inner edge. *\/ C[0] = B[3]; C[1] = B[2]; gvrender_polyline(job, C, 2); break; case FOLDER: \/* * Adjust the perimeter for the protrusions. * * D[2] +----+ D[1] * B[3]= \/ \\ * D[4] +--+----+ + + AF[0]=B[0]=D[0] * | B[2] D[3] B[1]| * B[4] + | * | | * B[5] + | * +----------------+ * *\/ \/* Add the folder edges. *\/ D = N_NEW(sides + 3, pointf); D[0] = AF[0]; D[1].x = AF[0].x - (AF[0].x - B[1].x) \/ 4; D[1].y = AF[0].y + (B[3].y - B[4].y) \/ 3; D[2].x = AF[0].x - 2 * (AF[0].x - B[1].x); D[2].y = D[1].y; D[3].x = AF[0].x - 2.25 * (AF[0].x - B[1].x); D[3].y = B[3].y; D[4].x = B[3].x; D[4].y = B[3].y; for (seg = 4; seg < sides + 3; seg++) D[seg] = AF[seg - 3]; gvrender_polygon(job, D, sides + 3, filled); free(D); break; case BOX3D: assert(sides == 4); \/* Adjust for the cutoff edges. *\/ D = N_NEW(sides + 2, pointf); D[0] = AF[0]; D[1] = B[2]; D[2] = B[4]; D[3] = AF[2]; D[4] = B[8]; D[5] = B[10]; gvrender_polygon(job, D, sides + 2, filled); free(D); \/* Draw the inner vertices. *\/ C[0].x = B[1].x + (B[11].x - B[0].x); C[0].y = B[1].y + (B[11].y - B[0].y); C[1] = B[4]; gvrender_polyline(job, C, 2); C[1] = B[8]; gvrender_polyline(job, C, 2); C[1] = B[0]; gvrender_polyline(job, C, 2); break; case COMPONENT: assert(sides == 4); \/* * Adjust the perimeter for the protrusions. * * D[1] +----------------+ D[0] * | | * 3+---+2 | * | | * 4+---+5 | * | | * 7+---+6 | * | | * 8+---+9 | * | | * 10+----------------+ D[11] * *\/ D = N_NEW(sides + 8, pointf); D[0] = AF[0]; D[1] = AF[1]; D[2].x = B[3].x + (B[4].x - B[3].x); D[2].y = B[3].y + (B[4].y - B[3].y); D[3].x = D[2].x + (B[3].x - B[2].x); D[3].y = D[2].y + (B[3].y - B[2].y); D[4].x = D[3].x + (B[4].x - B[3].x); D[4].y = D[3].y + (B[4].y - B[3].y); D[5].x = D[4].x + (D[2].x - D[3].x); D[5].y = D[4].y + (D[2].y - D[3].y); D[9].x = B[6].x + (B[5].x - B[6].x); D[9].y = B[6].y + (B[5].y - B[6].y); D[8].x = D[9].x + (B[6].x - B[7].x); D[8].y = D[9].y + (B[6].y - B[7].y); D[7].x = D[8].x + (B[5].x - B[6].x); D[7].y = D[8].y + (B[5].y - B[6].y); D[6].x = D[7].x + (D[9].x - D[8].x); D[6].y = D[7].y + (D[9].y - D[8].y); D[10] = AF[2]; D[11] = AF[3]; gvrender_polygon(job, D, sides + 8, filled); \/* Draw the internal vertices. *\/ C[0] = D[2]; C[1].x = D[2].x - (D[3].x - D[2].x); C[1].y = D[2].y - (D[3].y - D[2].y); C[2].x = C[1].x + (D[4].x - D[3].x); C[2].y = C[1].y + (D[4].y - D[3].y); C[3] = D[5]; gvrender_polyline(job, C, 4); C[0] = D[6]; C[1].x = D[6].x - (D[7].x - D[6].x); C[1].y = D[6].y - (D[7].y - D[6].y); C[2].x = C[1].x + (D[8].x - D[7].x); C[2].y = C[1].y + (D[8].y - D[7].y); C[3] = D[9]; gvrender_polyline(job, C, 4); free(D); break; case PROMOTER: \/* * L-shaped arrow on a center line, scales in the x direction * * * D[1] |\\ * +----------------+ \\ * | D[0] \\ * | \\ * | \/ * | D[5] \/ * | +-------+ \/ * | | |\/ * +--------+ *\/ \/* Add the tab edges. *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2 \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/the arrow's thickness is (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; \/\/the thickness is subituted with (AF[0].x - AF[1].x)\/8 to make it scalable in the y with label length D = N_NEW(sides + 5, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 + (AF[0].x - AF[1].x)\/8; \/\/x_center + width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)*3\/2; \/\/D[4].y + width D[1].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (AF[0].x - AF[1].x)\/4; \/\/x_center - 2*width D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/y_center D[3].x = D[2].x + (B[2].x - B[3].x)\/2; \/\/D[2].x + width D[3].y = AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/y_center D[4].x = D[3].x; D[4].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y); \/\/highest cds point D[5].x = D[0].x; D[5].y = D[4].y; \/\/highest cds point D[6].x = D[0].x; D[6].y = D[4].y - (B[3].y-B[4].y)\/4; \/\/D[4].y - width\/2 D[7].x = D[6].x + (B[2].x - B[3].x); \/\/D[6].x + 2*width D[7].y = D[6].y + (B[3].y - B[4].y)\/2; \/\/D[6].y + width D[8].x = D[0].x; D[8].y = D[0].y + (B[3].y - B[4].y)\/4;\/\/D[0].y + width\/2 gvrender_polygon(job, D, sides + 5, filled); \/*dsDNA line*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case CDS: \/* * arrow without the protrusions, scales normally * * * D[1] = AF[1] * +----------------+\\ * | D[0]\\ * | \\ * | \/ * | \/ * +----------------+\/ * D[3] * *\/ D = N_NEW(sides + 1, pointf); D[0].x = B[1].x; D[0].y = B[1].y - (B[3].y - B[4].y)\/2; D[1].x = B[3].x; D[1].y = B[3].y - (B[3].y - B[4].y)\/2; D[2].x = AF[2].x; D[2].y = AF[2].y + (B[3].y - B[4].y)\/2; D[3].x = B[1].x; D[3].y = AF[2].y + (B[3].y - B[4].y)\/2; D[4].y = AF[0].y - (AF[0].y - AF[3].y)\/2; D[4].x = AF[0].x; gvrender_polygon(job, D, sides + 1, filled); free(D); break; case TERMINATOR: \/* * T-shape, does not scale, always in the center * * * D[4] * +----------------+ * | D[3] * | | * | | * | D[6] D[1] | * D[5]+---+ +----+ D[2] * | | * +-------+ D[0] *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2 \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; D = N_NEW(sides + 4, pointf); D[0].x = AF[1].x + (AF[0].x-AF[1].x)\/2 + (B[2].x-B[3].x)\/4; \/\/x_center + width\/2 D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/y_center D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)\/2; D[2].x = D[1].x + (B[2].x-B[3].x)\/2; D[2].y = D[1].y; D[3].x = D[2].x; D[3].y = D[2].y + (B[3].y-B[4].y)\/2; D[4].x = AF[1].x + (AF[0].x-AF[1].x)\/2 - (B[2].x-B[3].x)*3\/4; \/\/D[3].y mirrowed across the center D[4].y = D[3].y; D[5].x = D[4].x; D[5].y = D[2].y; D[6].x = AF[1].x + (AF[0].x-AF[1].x)\/2 - (B[2].x-B[3].x)\/4; \/\/D[1].x mirrowed across the center D[6].y = D[1].y; D[7].x = D[6].x; D[7].y = D[0].y; gvrender_polygon(job, D, sides + 4, filled); \/*dsDNA line*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case UTR: \/* * half-octagon with line, does not scale, always in center * * D[3] * _____ D[2] * \/ \\ * \/ \\ D[1] * | | * ----------- * D[0] * * * *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2 \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; D = N_NEW(sides + 2, pointf); D[0].x = AF[1].x + (AF[0].x-AF[1].x)\/2 + (B[2].x-B[3].x)*3\/4; \/\/x_center+width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/y_center D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)\/4; \/\/D[0].y+width\/2 D[2].x = AF[1].x + (AF[0].x-AF[1].x)\/2 + (B[2].x-B[3].x)\/4; \/\/x_center+width\/2 D[2].y = D[1].y + (B[3].y-B[4].y)\/2; \/\/D[1].y+width D[3].x = AF[1].x + (AF[0].x-AF[1].x)\/2 - (B[2].x-B[3].x)\/4; \/\/D[2].x mirrowed across the center D[3].y = D[2].y; D[4].x = AF[1].x + (AF[0].x-AF[1].x)\/2 - (B[2].x-B[3].x)*3\/4; D[4].y = D[1].y; D[5].x = D[4].x; D[5].y = D[0].y; gvrender_polygon(job, D, sides + 2, filled); \/*dsDNA line*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case PRIMERSITE: \/* * half arrow shape, scales in the x-direction * D[1] * |\\ * | \\ * | \\ * ------------ \\ * | \\ * ------------------\\ D[0] * * -------------------------------- * *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; \/\/the thickness is subituted with (AF[0].x - AF[1].x)\/8 to make it scalable in the y with label length D = N_NEW(sides + 1, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 + (B[2].x-B[3].x);\/\/x_center + width*2 D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/4;\/\/y_center + 1\/2 width D[1].x = D[0].x - (B[2].x-B[3].x); \/\/x_center D[1].y = D[0].y + (B[3].y-B[4].y); D[2].x = D[1].x; D[2].y = D[0].y + (B[3].y-B[4].y)\/2; D[3].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (AF[0].x - AF[1].x)\/4;\/\/x_center - 2*(scalable width) D[3].y = D[2].y; D[4].x = D[3].x; D[4].y = D[0].y; gvrender_polygon(job, D, sides + 1, filled); \/*dsDNA line*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case RESTRICTIONSITE: \/* * zigzag shape, scales in the x-direction (only the middle section) * * * ----D[2] * | |________ D[0] * | |____ * ---------- | * D[4] --- D[7] * * * *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; \/\/the thickness is subituted with (AF[0].x - AF[1].x)\/8 to make it scalable in the y with label length D = N_NEW(sides + 4, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 + (AF[0].x - AF[1].x)\/8 + (B[2].x-B[3].x)\/2;\/\/x_center + scalable_width + width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/4;\/\/y_center + 1\/2 width D[1].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (AF[0].x - AF[1].x)\/8; \/\/x_center - width D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)\/2; D[3].x = D[2].x - (B[2].x-B[3].x)\/2; \/\/D[2].x - width D[3].y = D[2].y; D[4].x = D[3].x; D[4].y = AF[2].y + (AF[1].y - AF[2].y)\/2 - (B[3].y-B[4].y)\/4; \/\/y_center - 1\/2(width) D[5].x = D[0].x - (B[2].x-B[3].x)\/2; D[5].y = D[4].y; D[6].x = D[5].x; D[6].y = D[5].y - (B[3].y-B[4].y)\/2; D[7].x = D[0].x; D[7].y = D[6].y; gvrender_polygon(job, D, sides + 4, filled); \/*dsDNA line left half*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = D[4].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); \/*dsDNA line right half*\/ C[0].x = D[7].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case FIVEPOVERHANG: \/* * does not scale, on the left side * * D[3]------D[2] * | | * D[0]------D[1] * ----- ------------ * | | * D[0]--D[1] * * * *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; \/\/the thickness is subituted with (AF[0].x - AF[1].x)\/8 to make it scalable in the y with label length D = N_NEW(sides, pointf); D[0].x = AF[1].x;\/\/the very left edge D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/8;\/\/y_center + 1\/4 width D[1].x = D[0].x + 2*(B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)\/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); \/*second, lower shape*\/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (B[2].x-B[3].x); D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 - (B[3].y-B[4].y)*5\/8; \/\/y_center - 5\/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)\/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); \/*dsDNA line right half*\/ C[0].x = D[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case THREEPOVERHANG: \/* * does not scale, on the right side * * D[2]------D[1] * | | *----------D[3]------D[0] * ----- D[1] * | | * D[3]--D[0] * * * *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; \/\/the thickness is subituted with (AF[0].x - AF[1].x)\/8 to make it scalable in the y with label length D = N_NEW(sides, pointf); D[0].x = AF[0].x;\/\/the very right edge D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/8;\/\/y_center + 1\/4 width D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)\/2; D[2].x = D[1].x - 2*(B[3].y-B[4].y); D[2].y = D[1].y; D[3].x = D[2].x; D[3].y = D[0].y; gvrender_polygon(job, D, sides, filled); \/*second, lower shape*\/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[0].x - (B[2].x-B[3].x); D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 - (B[3].y-B[4].y)*5\/8; \/\/y_center - 5\/4 width D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)\/2; D[2].x = D[1].x - (B[3].y-B[4].y); D[2].y = D[1].y; D[3].x = D[2].x; D[3].y = D[0].y; gvrender_polygon(job, D, sides, filled); \/*dsDNA line left half*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = D[3].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case NOVERHANG: \/* * does not scale * * D[3]------D[2] D[3]------D[2] * | | | | * ---D[0]------D[1] D[0]------D[1]---- * D[3]------D[2] D[3]------D[2] * | | | | * D[0]------D[1] D[0]------D[1] * * * * *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; \/\/the thickness is subituted with (AF[0].x - AF[1].x)\/8 to make it scalable in the y with label length \/*upper left rectangle*\/ D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (B[2].x-B[3].x)*9\/8; \/\/x_center - 2*width - 1\/4*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/8;\/\/y_center + 1\/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)\/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); \/*lower, left rectangle*\/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (B[2].x-B[3].x)*9\/8; \/\/x_center - 2*width - 1\/4*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 - (B[3].y-B[4].y)*5\/8;\/\/y_center - width - 1\/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)\/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); \/*lower, right rectangle*\/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 + (B[2].x-B[3].x)\/8; \/\/x_center + 1\/4*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 - (B[3].y-B[4].y)*5\/8;\/\/y_center - width - 1\/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)\/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); \/*upper, right rectangle*\/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 + (B[2].x-B[3].x)\/8; \/\/x_center + 1\/4*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/8;\/\/y_center - width - 1\/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)\/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); \/*dsDNA line right half*\/ C[0].x = D[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); \/*dsDNA line left half*\/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (B[2].x-B[3].x)*9\/8; \/\/D[0].x of of the left rectangles C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[1].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case ASSEMBLY: \/* * does not scale * * D[3]----------D[2] * | | * D[0]----------D[1] * ---- --------- * D[3]----------D[2] * | | * D[0]----------D[1] * *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; \/\/the thickness is subituted with (AF[0].x - AF[1].x)\/8 to make it scalable in the y with label length D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (B[2].x-B[3].x); \/\/x_center - 2*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/8;\/\/y_center + 1\/4 width D[1].x = D[0].x + 2*(B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)\/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); \/*second, lower shape*\/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (B[2].x-B[3].x); \/\/x_center - 2*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 - (B[3].y-B[4].y)*5\/8;\/\/y_center - width - 1\/4 width D[1].x = D[0].x + 2*(B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)\/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); \/*dsDNA line right half*\/ C[0].x = D[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); \/*dsDNA line left half*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = D[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case SIGNATURE: \/* * * * +--------------+ * | | * |x | * |_____________ | * +--------------+ *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; \/\/the thickness is subituted with (AF[0].x - AF[1].x)\/8 to make it scalable in the y with label length D = N_NEW(sides, pointf); D[0].x = AF[0].x; D[0].y = B[1].y - (B[3].y - B[4].y)\/2; D[1].x = B[3].x; D[1].y = B[3].y - (B[3].y - B[4].y)\/2; D[2].x = AF[2].x; D[2].y = AF[2].y + (B[3].y - B[4].y)\/2; D[3].x = AF[0].x; D[3].y = AF[2].y + (B[3].y - B[4].y)\/2; gvrender_polygon(job, D, sides, filled); \/* \"\\\" of the X*\/ C[0].x = AF[1].x + (B[2].x-B[3].x)\/4; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/8; \/\/y_center + 1\/4 width C[1].x = C[0].x + (B[2].x-B[3].x)\/4;\/\/C[0].x + width\/2 C[1].y = C[0].y - (B[3].y-B[4].y)\/4;\/\/C[0].y - width\/2 gvrender_polyline(job, C, 2); \/*\"\/\" of the X*\/ C[0].x = AF[1].x + (B[2].x-B[3].x)\/4; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 - (B[3].y-B[4].y)\/8; \/\/y_center - 1\/4 width C[1].x = C[0].x + (B[2].x-B[3].x)\/4;\/\/C[0].x + width\/2 C[1].y = C[0].y + (B[3].y-B[4].y)\/4;\/\/C[0].y + width\/2 gvrender_polyline(job, C, 2); \/*bottom line*\/ C[0].x = AF[1].x + (B[2].x-B[3].x)\/4; C[0].y = AF[2].y + (B[3].y-B[4].y)*3\/4; C[1].x = AF[0].x - (B[2].x-B[3].x)\/4; C[1].y = C[0].y; gvrender_polyline(job, C, 2); free(D); break; case INSULATOR: \/* * double square * * +-----+ *--| ___ |--- * | |_| | * +-----+ * *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2 \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 + (B[2].x-B[3].x)\/2; \/\/x_center+width D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[2].x-B[3].x)\/2; \/\/y_center D[1].x = D[0].x; D[1].y = AF[2].y + (AF[1].y - AF[2].y)\/2 - (B[2].x-B[3].x)\/2; \/\/D[0].y- width D[2].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (B[2].x-B[3].x)\/2; \/\/x_center-width D[2].y = D[1].y; D[3].x = D[2].x; D[3].y = D[0].y; gvrender_polygon(job, D, sides, filled); free(D); \/*outer square line*\/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 + (B[2].x-B[3].x)*3\/4; \/\/x_center+1.5*width C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[2].x-B[3].x)*3\/4; \/\/y_center C[1].x = C[0].x; C[1].y = AF[2].y + (AF[1].y - AF[2].y)\/2 - (B[2].x-B[3].x)*3\/4; \/\/y_center- 1.5*width C[2].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (B[2].x-B[3].x)*3\/4; \/\/x_center-1.5*width C[2].y = C[1].y; C[3].x = C[2].x; C[3].y = C[0].y; C[4] = C[0]; gvrender_polyline(job, C, 5); \/*dsDNA line right half*\/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2 + (B[2].x-B[3].x)*3\/4; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); \/*dsDNA line left half*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[1].x + (AF[0].x - AF[1].x)\/2 - (B[2].x-B[3].x)*3\/4; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); break; case RIBOSITE: \/* * X with a dashed line on the bottom * * * X * | * ------------ *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2 \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; D = N_NEW(sides + 12, pointf); \/\/12-sided x D[0].x = AF[1].x + (AF[0].x-AF[1].x)\/2 + (B[2].x-B[3].x)\/4; \/\/x_center+widtht\/2 , lower right corner of the x D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/2; \/\/y_center + width D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)\/8; \/\/D[0].y +width\/4 D[2].x = D[0].x - (B[2].x-B[3].x)\/8; \/\/D[0].x- width\/4 \/\/right nook of the x D[2].y = D[1].y + (B[3].y-B[4].y)\/8; \/\/D[0].y+width\/2 or D[1].y+width\/4 D[3].x = D[0].x; D[3].y = D[2].y + (B[3].y-B[4].y)\/8; \/\/D[2].y + width\/4 D[4].x = D[0].x; D[4].y = D[3].y + (B[3].y-B[4].y)\/8; \/\/top right corner of the x D[5].x = D[2].x; D[5].y = D[4].y; D[6].x = AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/x_center D[6].y = D[3].y; \/\/top nook D[7].x = D[6].x - (B[2].x-B[3].x)\/8; \/\/D[5] mirrowed across y D[7].y = D[5].y; D[8].x = D[7].x - (B[2].x-B[3].x)\/8;\/\/top left corner D[8].y = D[7].y; D[9].x = D[8].x; D[9].y = D[3].y; D[10].x = D[8].x + (B[2].x-B[3].x)\/8; D[10].y = D[2].y; D[11].x = D[8].x; D[11].y = D[1].y; D[12].x = D[8].x; D[12].y = D[0].y; D[13].x = D[10].x; D[13].y = D[12].y; D[14].x = D[6].x; \/\/bottom nook D[14].y = D[1].y; D[15].x = D[2].x; D[15].y = D[0].y; gvrender_polygon(job, D, sides + 12, filled); \/\/2-part dash line \/*line below the x, bottom dash*\/ C[0].x = D[14].x; \/\/x_center C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/y_center C[1].x = C[0].x; C[1].y = C[0].y + (B[3].y-B[4].y)\/8; \/\/y_center + 1\/4*width gvrender_polyline(job, C, 2); \/*line below the x, top dash*\/ C[0].x = D[14].x; \/\/x_center C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/4; C[1].x = C[0].x; C[1].y = C[0].y + (B[3].y-B[4].y)\/8; gvrender_polyline(job, C, 2); \/*dsDNA line*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case RNASTAB: \/* * hexagon with a dashed line on the bottom * * * O * | * ------------ *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2 \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; D = N_NEW(sides + 4, pointf); \/\/12-sided x D[0].x = AF[1].x + (AF[0].x-AF[1].x)\/2 + (B[2].x-B[3].x)\/8; \/\/x_center+widtht\/8 , lower right corner of the hexagon D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/2; \/\/y_center + width D[1].x = D[0].x + (B[2].x-B[3].x)\/8; D[1].y = D[0].y + (B[3].y-B[4].y)\/8; \/\/D[0].y +width\/4 D[2].x = D[1].x; \/\/D[0].x- width\/4 D[2].y = D[1].y + (B[3].y-B[4].y)\/4; \/\/D[1].y+width\/2 D[3].x = D[0].x; D[3].y = D[2].y + (B[3].y-B[4].y)\/8; \/\/D[2].y + width\/4 D[4].x = D[3].x - (B[2].x-B[3].x)\/4; D[4].y = D[3].y; \/\/top of the hexagon D[5].x = D[4].x - (B[2].x-B[3].x)\/8; D[5].y = D[2].y; D[6].x = D[5].x; D[6].y = D[1].y; \/\/left side D[7].x = D[4].x; D[7].y = D[0].y; \/\/bottom gvrender_polygon(job, D, sides + 4, filled); \/\/2-part dash line \/*line below the x, bottom dash*\/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/x_center C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/y_center C[1].x = C[0].x; C[1].y = C[0].y + (B[3].y-B[4].y)\/8; \/\/y_center + 1\/4*width gvrender_polyline(job, C, 2); \/*line below the x, top dash*\/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/x_center C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/4; C[1].x = C[0].x; C[1].y = C[0].y + (B[3].y-B[4].y)\/8; gvrender_polyline(job, C, 2); \/*dsDNA line*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case PROTEASESITE: \/* * X with a solid line on the bottom * * * X * | * ------------ *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2 \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; D = N_NEW(sides + 12, pointf); \/\/12-sided x D[0].x = AF[1].x + (AF[0].x-AF[1].x)\/2 + (B[2].x-B[3].x)\/4; \/\/x_center+widtht\/2 , lower right corner of the x D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/2; \/\/y_center + width D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)\/8; \/\/D[0].y +width\/4 D[2].x = D[0].x - (B[2].x-B[3].x)\/8; \/\/D[0].x- width\/4 \/\/right nook of the x D[2].y = D[1].y + (B[3].y-B[4].y)\/8; \/\/D[0].y+width\/2 or D[1].y+width\/4 D[3].x = D[0].x; D[3].y = D[2].y + (B[3].y-B[4].y)\/8; \/\/D[2].y + width\/4 D[4].x = D[0].x; D[4].y = D[3].y + (B[3].y-B[4].y)\/8; \/\/top right corner of the x D[5].x = D[2].x; D[5].y = D[4].y; D[6].x = AF[1].x + (AF[0].x - AF[1].x)\/2; \/\/x_center D[6].y = D[3].y; \/\/top nook D[7].x = D[6].x - (B[2].x-B[3].x)\/8; \/\/D[5] mirrowed across y D[7].y = D[5].y; D[8].x = D[7].x - (B[2].x-B[3].x)\/8;\/\/top left corner D[8].y = D[7].y; D[9].x = D[8].x; D[9].y = D[3].y; D[10].x = D[8].x + (B[2].x-B[3].x)\/8; D[10].y = D[2].y; D[11].x = D[8].x; D[11].y = D[1].y; D[12].x = D[8].x; D[12].y = D[0].y; D[13].x = D[10].x; D[13].y = D[12].y; D[14].x = D[6].x; \/\/bottom nook D[14].y = D[1].y; D[15].x = D[2].x; D[15].y = D[0].y; gvrender_polygon(job, D, sides + 12, filled); \/*line below the x*\/ C[0] = D[14]; C[1].x = C[0].x; C[1].y = AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/y_center gvrender_polyline(job, C, 2); \/*dsDNA line*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case PROTEINSTAB: \/* * hexagon with a dashed line on the bottom * * * O * | * ------------ *\/ \/\/x_center is AF[1].x + (AF[0].x - AF[1].x)\/2 \/\/y_center is AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/width units are (B[2].x-B[3].x)\/2 or (B[3].y-B[4].y)\/2; D = N_NEW(sides + 4, pointf); \/\/12-sided x D[0].x = AF[1].x + (AF[0].x-AF[1].x)\/2 + (B[2].x-B[3].x)\/8; \/\/x_center+widtht\/8 , lower right corner of the hexagon D[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2 + (B[3].y-B[4].y)\/2; \/\/y_center + width D[1].x = D[0].x + (B[2].x-B[3].x)\/8; D[1].y = D[0].y + (B[3].y-B[4].y)\/8; \/\/D[0].y +width\/4 D[2].x = D[1].x; \/\/D[0].x- width\/4 D[2].y = D[1].y + (B[3].y-B[4].y)\/4; \/\/D[1].y+width\/2 D[3].x = D[0].x; D[3].y = D[2].y + (B[3].y-B[4].y)\/8; \/\/D[2].y + width\/4 D[4].x = D[3].x - (B[2].x-B[3].x)\/4; D[4].y = D[3].y; \/\/top of the hexagon D[5].x = D[4].x - (B[2].x-B[3].x)\/8; D[5].y = D[2].y; D[6].x = D[5].x; D[6].y = D[1].y; \/\/left side D[7].x = D[4].x; D[7].y = D[0].y; \/\/bottom gvrender_polygon(job, D, sides + 4, filled); \/*line below the x*\/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)\/2; C[0].y = D[0].y; C[1].x = C[0].x; C[1].y = AF[2].y + (AF[1].y - AF[2].y)\/2; \/\/y_center gvrender_polyline(job, C, 2); \/*dsDNA line*\/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)\/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)\/2; gvrender_polyline(job, C, 2); free(D); break; case RPROMOTER: \/* * Adjust the perimeter for the protrusions. * * * D[1] = AF[1] |\\ * +----------------+ \\ * | D[0] \\ * | \\ * | \/ * | \/ * | +-------+ \/ * | | |\/ * +--------+ *\/ \/* Add the tab edges. *\/ D = N_NEW(sides + 5, pointf); \/*5 new points*\/ D[0].x = B[1].x - (B[2].x - B[3].x)\/2; D[0].y = B[1].y - (B[3].y - B[4].y)\/2; D[1].x = B[3].x; D[1].y = B[3].y - (B[3].y - B[4].y)\/2; D[2].x = AF[2].x; D[2].y = AF[2].y; D[3].x = B[2].x + (B[2].x - B[3].x)\/2; D[3].y = AF[2].y; D[4].x = B[2].x + (B[2].x - B[3].x)\/2; D[4].y = AF[2].y + (B[3].y - B[4].y)\/2; D[5].x = B[1].x - (B[2].x - B[3].x)\/2; D[5].y = AF[2].y + (B[3].y - B[4].y)\/2; D[6].x = B[1].x - (B[2].x - B[3].x)\/2; D[6].y = AF[3].y; D[7].y = AF[0].y - (AF[0].y - AF[3].y)\/2; \/*triangle point *\/ D[7].x = AF[0].x; \/*triangle point *\/ D[8].y = AF[0].y; D[8].x = B[1].x - (B[2].x - B[3].x)\/2; gvrender_polygon(job, D, sides + 5, filled); free(D); break; case RARROW: \/* * Adjust the perimeter for the protrusions. * * * D[1] = AF[1] |\\ * +----------------+ \\ * | D[0] \\ * | \\ * | \/ * | \/ * +----------------+ \/ * |\/ * *\/ \/* Add the tab edges. *\/ D = N_NEW(sides + 3, pointf); \/*3 new points*\/ D[0].x = B[1].x - (B[2].x - B[3].x)\/2; D[0].y = B[1].y - (B[3].y - B[4].y)\/2; D[1].x = B[3].x; D[1].y = B[3].y - (B[3].y - B[4].y)\/2; D[2].x = AF[2].x; D[2].y = AF[2].y + (B[3].y - B[4].y)\/2; D[3].x = B[1].x - (B[2].x - B[3].x)\/2; D[3].y = AF[2].y + (B[3].y - B[4].y)\/2; D[4].x = B[1].x - (B[2].x - B[3].x)\/2; D[4].y = AF[3].y; D[5].y = AF[0].y - (AF[0].y - AF[3].y)\/2;\/*triangle point*\/ D[5].x = AF[0].x; \/*triangle point *\/ D[6].y = AF[0].y; D[6].x = B[1].x - (B[2].x - B[3].x)\/2; gvrender_polygon(job, D, sides + 3, filled); free(D); break; case LARROW: \/* * Adjust the perimeter for the protrusions. * * * \/| * \/ +----------------+ * \/ | * \\ | * \\ +----------------+ * \\| * *\/ \/* Add the tab edges. *\/ D = N_NEW(sides + 3, pointf); \/*3 new points*\/ D[0].x = AF[0].x; D[0].y = AF[0].y - (B[3].y-B[4].y)\/2; D[1].x = B[2].x + (B[2].x - B[3].x)\/2; D[1].y = AF[0].y - (B[3].y-B[4].y)\/2;\/*D[0].y*\/ D[2].x = B[2].x + (B[2].x - B[3].x)\/2;\/*D[1].x*\/ D[2].y = B[2].y; D[3].x = AF[1].x; \/*triangle point*\/ D[3].y = AF[1].y - (AF[1].y - AF[2].y)\/2; \/*triangle point*\/ D[4].x = B[2].x + (B[2].x - B[3].x)\/2;\/*D[1].x*\/ D[4].y = AF[2].y; D[5].y = AF[2].y + (B[3].y-B[4].y)\/2; D[5].x = B[2].x + (B[2].x - B[3].x)\/2;\/*D[1].x*\/ D[6].y = AF[3].y + (B[3].y - B[4].y)\/2; D[6].x = AF[0].x;\/*D[0]*\/ gvrender_polygon(job, D, sides + 3, filled); free(D); break; case LPROMOTER: \/* * Adjust the perimeter for the protrusions. * * * \/| * \/ +----------------+ * \/ D[0] * \/ | * \\ | * \\ | * \\ +--------+ + * \\| | | * +-------+ *\/ \/* Add the tab edges. *\/ D = N_NEW(sides + 5, pointf); \/*3 new points*\/ D[0].x = AF[0].x; D[0].y = AF[0].y - (B[3].y-B[4].y)\/2; D[1].x = B[2].x + (B[2].x - B[3].x)\/2; D[1].y = AF[0].y - (B[3].y-B[4].y)\/2;\/*D[0].y*\/ D[2].x = B[2].x + (B[2].x - B[3].x)\/2;\/*D[1].x*\/ D[2].y = B[2].y; D[3].x = AF[1].x; \/*triangle point*\/ D[3].y = AF[1].y - (AF[1].y - AF[2].y)\/2; \/*triangle point*\/ D[4].x = B[2].x + (B[2].x - B[3].x)\/2;\/*D[1].x*\/ D[4].y = AF[2].y; D[5].y = AF[2].y + (B[3].y-B[4].y)\/2; D[5].x = B[2].x + (B[2].x - B[3].x)\/2;\/*D[1].x*\/ D[6].y = AF[3].y + (B[3].y - B[4].y)\/2; D[6].x = B[1].x - (B[2].x - B[3].x)\/2; D[7].x = B[1].x - (B[2].x - B[3].x)\/2;\/*D[6].x*\/ D[7].y = AF[3].y; D[8].x = AF[3].x; D[8].y = AF[3].y; gvrender_polygon(job, D, sides + 5, filled); free(D); break; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":438628,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (*p && ((p-chunk) < (ssize_t) length)) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { if (prev != (Quantum *) NULL) prev=(Quantum *) RelinquishMagickMemory(prev); if (next != (Quantum *) NULL) next=(Quantum *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (Quantum *) NULL) break; q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":435362,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char *name, s[2]; const char *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if ((image->storage_class != PseudoClass) && (image->colormap != (PixelInfo *) NULL)) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; if (image->depth != GetImageDepth(image,exception)) (void) SetImageDepth(image,image->depth,exception); for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *r; register Quantum *q; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < MagickMin(image->colors,256); i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { r=GetVirtualPixels(image,0,y,image->columns,1,exception); if (r == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,r) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image,r,opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,r,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image,r,opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,r) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image,r,transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,r); ping_trans_color.green=(unsigned short) GetPixelGreen(image,r); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,r); ping_trans_color.gray=(unsigned short) GetPixelGray(image,r); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,r,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,r,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,r,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,r,semitransparent+i) && GetPixelAlpha(image,r) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image,r,semitransparent+i); } } } r+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } if (number_opaque < 259) { for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != GetPixelGreen(image,r) || GetPixelRed(image,r) != GetPixelBlue(image,r)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != 0 && GetPixelRed(image,r) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,q); SetPixelAlpha(image,TransparentAlpha,q); } else SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR04PixelRGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR03RGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR02PixelBlue(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,q)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,q)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,q)) == 0x00 && GetPixelAlpha(image,q) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } (void) old_bit_depth; image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); \/* write orNT if image->orientation is defined *\/ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); \/* data length=1 *\/ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); \/* PNG uses Exif orientation values *\/ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,GetPixelChannels(image)* sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(ping_pixels,0,rowbytes*GetPixelChannels(image)* sizeof(*ping_pixels)); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) || ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse)) { \/* Palette, Bilevel, or Opaque Monochrome *\/ QuantumType quantum_type; register const Quantum *p; quantum_type=RedQuantum; if (mng_info->IsPalette) { quantum_type=GrayQuantum; if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) quantum_type=IndexQuantum; } SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,ping_pixels,exception); if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":200401,"input":"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 *\/","output":{"is_vulnerable":"True","vulnerability_types":["Integer Overflow or Wraparound"],"explanation":"Perl before 5.30.3 on 32-bit platforms allows a heap-based buffer overflow because nested regular expression quantifiers have an integer overflow.","severity_level":"NoInfo","cwe":"CWE-190","cve":"CVE-2020-10543"}} -{"idx":211649,"input":"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 *\/","output":{"is_vulnerable":"True","vulnerability_types":["Integer Overflow or Wraparound"],"explanation":"Perl before 5.30.3 has an integer overflow related to mishandling of a \"PL_regkind[OP(n)] == NOTHING\" situation. A crafted regular expression could lead to malformed bytecode with a possibility of instruction injection.","severity_level":"NoInfo","cwe":"CWE-190","cve":"CVE-2020-10878"}} -{"idx":438627,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (Magick_png_color_equal(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (Magick_png_color_equal(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (Magick_png_color_equal(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", IMimage->filename); } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); \/* write orNT if image->orientation is defined *\/ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); \/* data length=1 *\/ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); \/* PNG uses Exif orientation values *\/ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { \/* Palette, Bilevel, or Opaque Monochrome *\/ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { \/* Undo pixel scaling *\/ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":10592,"input":"yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else \/* ! YYPARSE_PARAM *\/ #if (defined __STDC__ || defined __C99__FUNC__ \\ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { int yystate; \/* Number of tokens to shift before error messages enabled. *\/ int yyerrstatus; \/* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. *\/ \/* The state stack. *\/ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; \/* The semantic value stack. *\/ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; \/* Lookahead token as an internal (translated) token number. *\/ int yytoken; \/* The variables used to return semantic value and location from the action routines. *\/ YYSTYPE yyval; #if YYERROR_VERBOSE \/* Buffer for error messages, and its allocated size. *\/ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) \/* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. *\/ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, \"Starting parse\\n\")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; \/* Cause a token to be read. *\/ \/* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. *\/ yyssp = yyss; yyvsp = yyvs; goto yysetstate; \/*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*\/ yynewstate: \/* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. *\/ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { \/* Get the current used size of the three stacks, in elements. *\/ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { \/* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. *\/ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; \/* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. *\/ yyoverflow (YY_(\"memory exhausted\"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else \/* no yyoverflow *\/ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else \/* Extend the stack our own way. *\/ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif \/* no yyoverflow *\/ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, \"Stack size increased to %lu\\n\", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, \"Entering state %d\\n\", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; \/*-----------. | yybackup. | `-----------*\/ yybackup: \/* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. *\/ \/* First try to decide what to do without reference to lookahead token. *\/ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; \/* Not known => get a lookahead token if don't already have one. *\/ \/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. *\/ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, \"Reading a token: \")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, \"Now at end of input.\\n\")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT (\"Next token is\", yytoken, &yylval, &yylloc); } \/* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. *\/ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } \/* Count tokens shifted since error; after three, turn off error status. *\/ if (yyerrstatus) yyerrstatus--; \/* Shift the lookahead token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yytoken, &yylval, &yylloc); \/* Discard the shifted token. *\/ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; \/*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*\/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; \/*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*\/ yyreduce: \/* yyn is the number of a rule to reduce with. *\/ yylen = yyr2[yyn]; \/* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. *\/ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: \/* Line 1455 of yacc.c *\/ #line 320 \"ntp_parser.y\" { \/* I will need to incorporate much more fine grained * error messages. The following should suffice for * the time being. *\/ msyslog(LOG_ERR, \"syntax error in %s line %d, column %d\", ip_file->fname, ip_file->err_line_no, ip_file->err_col_no); } break; case 19: \/* Line 1455 of yacc.c *\/ #line 354 \"ntp_parser.y\" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (3)].Integer), (yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue)); if (my_node) enqueue(cfgt.peers, my_node); } break; case 20: \/* Line 1455 of yacc.c *\/ #line 360 \"ntp_parser.y\" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node), NULL); if (my_node) enqueue(cfgt.peers, my_node); } break; case 27: \/* Line 1455 of yacc.c *\/ #line 377 \"ntp_parser.y\" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET); } break; case 28: \/* Line 1455 of yacc.c *\/ #line 378 \"ntp_parser.y\" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET6); } break; case 29: \/* Line 1455 of yacc.c *\/ #line 382 \"ntp_parser.y\" { (yyval.Address_node) = create_address_node((yyvsp[(1) - (1)].String), 0); } break; case 30: \/* Line 1455 of yacc.c *\/ #line 386 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 31: \/* Line 1455 of yacc.c *\/ #line 387 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 32: \/* Line 1455 of yacc.c *\/ #line 391 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 33: \/* Line 1455 of yacc.c *\/ #line 392 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 34: \/* Line 1455 of yacc.c *\/ #line 393 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 35: \/* Line 1455 of yacc.c *\/ #line 394 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 36: \/* Line 1455 of yacc.c *\/ #line 395 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 37: \/* Line 1455 of yacc.c *\/ #line 396 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 38: \/* Line 1455 of yacc.c *\/ #line 397 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 39: \/* Line 1455 of yacc.c *\/ #line 398 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 40: \/* Line 1455 of yacc.c *\/ #line 399 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 41: \/* Line 1455 of yacc.c *\/ #line 400 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 42: \/* Line 1455 of yacc.c *\/ #line 401 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 43: \/* Line 1455 of yacc.c *\/ #line 402 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 44: \/* Line 1455 of yacc.c *\/ #line 403 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 45: \/* Line 1455 of yacc.c *\/ #line 404 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 46: \/* Line 1455 of yacc.c *\/ #line 405 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 47: \/* Line 1455 of yacc.c *\/ #line 415 \"ntp_parser.y\" { struct unpeer_node *my_node = create_unpeer_node((yyvsp[(2) - (2)].Address_node)); if (my_node) enqueue(cfgt.unpeers, my_node); } break; case 50: \/* Line 1455 of yacc.c *\/ #line 434 \"ntp_parser.y\" { cfgt.broadcastclient = 1; } break; case 51: \/* Line 1455 of yacc.c *\/ #line 436 \"ntp_parser.y\" { append_queue(cfgt.manycastserver, (yyvsp[(2) - (2)].Queue)); } break; case 52: \/* Line 1455 of yacc.c *\/ #line 438 \"ntp_parser.y\" { append_queue(cfgt.multicastclient, (yyvsp[(2) - (2)].Queue)); } break; case 53: \/* Line 1455 of yacc.c *\/ #line 449 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 54: \/* Line 1455 of yacc.c *\/ #line 451 \"ntp_parser.y\" { cfgt.auth.control_key = (yyvsp[(2) - (2)].Integer); } break; case 55: \/* Line 1455 of yacc.c *\/ #line 453 \"ntp_parser.y\" { cfgt.auth.cryptosw++; append_queue(cfgt.auth.crypto_cmd_list, (yyvsp[(2) - (2)].Queue)); } break; case 56: \/* Line 1455 of yacc.c *\/ #line 458 \"ntp_parser.y\" { cfgt.auth.keys = (yyvsp[(2) - (2)].String); } break; case 57: \/* Line 1455 of yacc.c *\/ #line 460 \"ntp_parser.y\" { cfgt.auth.keysdir = (yyvsp[(2) - (2)].String); } break; case 58: \/* Line 1455 of yacc.c *\/ #line 462 \"ntp_parser.y\" { cfgt.auth.request_key = (yyvsp[(2) - (2)].Integer); } break; case 59: \/* Line 1455 of yacc.c *\/ #line 464 \"ntp_parser.y\" { cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); } break; case 60: \/* Line 1455 of yacc.c *\/ #line 466 \"ntp_parser.y\" { cfgt.auth.trusted_key_list = (yyvsp[(2) - (2)].Queue); } break; case 61: \/* Line 1455 of yacc.c *\/ #line 468 \"ntp_parser.y\" { cfgt.auth.ntp_signd_socket = (yyvsp[(2) - (2)].String); } break; case 63: \/* Line 1455 of yacc.c *\/ #line 474 \"ntp_parser.y\" { (yyval.Queue) = create_queue(); } break; case 64: \/* Line 1455 of yacc.c *\/ #line 479 \"ntp_parser.y\" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 65: \/* Line 1455 of yacc.c *\/ #line 486 \"ntp_parser.y\" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 66: \/* Line 1455 of yacc.c *\/ #line 496 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 67: \/* Line 1455 of yacc.c *\/ #line 498 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 68: \/* Line 1455 of yacc.c *\/ #line 500 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 69: \/* Line 1455 of yacc.c *\/ #line 502 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 70: \/* Line 1455 of yacc.c *\/ #line 504 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 71: \/* Line 1455 of yacc.c *\/ #line 506 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 72: \/* Line 1455 of yacc.c *\/ #line 508 \"ntp_parser.y\" { (yyval.Attr_val) = NULL; cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); msyslog(LOG_WARNING, \"'crypto revoke %d' is deprecated, \" \"please use 'revoke %d' instead.\", cfgt.auth.revoke, cfgt.auth.revoke); } break; case 73: \/* Line 1455 of yacc.c *\/ #line 525 \"ntp_parser.y\" { append_queue(cfgt.orphan_cmds,(yyvsp[(2) - (2)].Queue)); } break; case 74: \/* Line 1455 of yacc.c *\/ #line 529 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 75: \/* Line 1455 of yacc.c *\/ #line 530 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 76: \/* Line 1455 of yacc.c *\/ #line 535 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 77: \/* Line 1455 of yacc.c *\/ #line 537 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 78: \/* Line 1455 of yacc.c *\/ #line 539 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 79: \/* Line 1455 of yacc.c *\/ #line 541 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 80: \/* Line 1455 of yacc.c *\/ #line 543 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 81: \/* Line 1455 of yacc.c *\/ #line 545 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 82: \/* Line 1455 of yacc.c *\/ #line 547 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 83: \/* Line 1455 of yacc.c *\/ #line 549 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 84: \/* Line 1455 of yacc.c *\/ #line 551 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 85: \/* Line 1455 of yacc.c *\/ #line 553 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 86: \/* Line 1455 of yacc.c *\/ #line 555 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 87: \/* Line 1455 of yacc.c *\/ #line 565 \"ntp_parser.y\" { append_queue(cfgt.stats_list, (yyvsp[(2) - (2)].Queue)); } break; case 88: \/* Line 1455 of yacc.c *\/ #line 567 \"ntp_parser.y\" { if (input_from_file) cfgt.stats_dir = (yyvsp[(2) - (2)].String); else { free((yyvsp[(2) - (2)].String)); yyerror(\"statsdir remote configuration ignored\"); } } break; case 89: \/* Line 1455 of yacc.c *\/ #line 576 \"ntp_parser.y\" { enqueue(cfgt.filegen_opts, create_filegen_node((yyvsp[(2) - (3)].Integer), (yyvsp[(3) - (3)].Queue))); } break; case 90: \/* Line 1455 of yacc.c *\/ #line 583 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 91: \/* Line 1455 of yacc.c *\/ #line 584 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 100: \/* Line 1455 of yacc.c *\/ #line 600 \"ntp_parser.y\" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 101: \/* Line 1455 of yacc.c *\/ #line 607 \"ntp_parser.y\" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 102: \/* Line 1455 of yacc.c *\/ #line 617 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); else { (yyval.Attr_val) = NULL; free((yyvsp[(2) - (2)].String)); yyerror(\"filegen file remote configuration ignored\"); } } break; case 103: \/* Line 1455 of yacc.c *\/ #line 627 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); else { (yyval.Attr_val) = NULL; yyerror(\"filegen type remote configuration ignored\"); } } break; case 104: \/* Line 1455 of yacc.c *\/ #line 636 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror(\"filegen link remote configuration ignored\"); } } break; case 105: \/* Line 1455 of yacc.c *\/ #line 645 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror(\"filegen nolink remote configuration ignored\"); } } break; case 106: \/* Line 1455 of yacc.c *\/ #line 653 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 107: \/* Line 1455 of yacc.c *\/ #line 654 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 115: \/* Line 1455 of yacc.c *\/ #line 674 \"ntp_parser.y\" { append_queue(cfgt.discard_opts, (yyvsp[(2) - (2)].Queue)); } break; case 116: \/* Line 1455 of yacc.c *\/ #line 678 \"ntp_parser.y\" { append_queue(cfgt.mru_opts, (yyvsp[(2) - (2)].Queue)); } break; case 117: \/* Line 1455 of yacc.c *\/ #line 682 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (3)].Address_node), NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 118: \/* Line 1455 of yacc.c *\/ #line 687 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (5)].Address_node), (yyvsp[(4) - (5)].Address_node), (yyvsp[(5) - (5)].Queue), ip_file->line_no)); } break; case 119: \/* Line 1455 of yacc.c *\/ #line 692 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node(NULL, NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 120: \/* Line 1455 of yacc.c *\/ #line 697 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup(\"0.0.0.0\"), AF_INET), create_address_node( estrdup(\"0.0.0.0\"), AF_INET), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 121: \/* Line 1455 of yacc.c *\/ #line 710 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup(\"::\"), AF_INET6), create_address_node( estrdup(\"::\"), AF_INET6), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 122: \/* Line 1455 of yacc.c *\/ #line 723 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node( NULL, NULL, enqueue((yyvsp[(3) - (3)].Queue), create_ival((yyvsp[(2) - (3)].Integer))), ip_file->line_no)); } break; case 123: \/* Line 1455 of yacc.c *\/ #line 734 \"ntp_parser.y\" { (yyval.Queue) = create_queue(); } break; case 124: \/* Line 1455 of yacc.c *\/ #line 736 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 139: \/* Line 1455 of yacc.c *\/ #line 758 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 140: \/* Line 1455 of yacc.c *\/ #line 760 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 141: \/* Line 1455 of yacc.c *\/ #line 764 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 142: \/* Line 1455 of yacc.c *\/ #line 765 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 143: \/* Line 1455 of yacc.c *\/ #line 766 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 144: \/* Line 1455 of yacc.c *\/ #line 771 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 145: \/* Line 1455 of yacc.c *\/ #line 773 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 146: \/* Line 1455 of yacc.c *\/ #line 777 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 147: \/* Line 1455 of yacc.c *\/ #line 778 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 148: \/* Line 1455 of yacc.c *\/ #line 779 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 149: \/* Line 1455 of yacc.c *\/ #line 780 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 150: \/* Line 1455 of yacc.c *\/ #line 781 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 151: \/* Line 1455 of yacc.c *\/ #line 782 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 152: \/* Line 1455 of yacc.c *\/ #line 783 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 153: \/* Line 1455 of yacc.c *\/ #line 784 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 154: \/* Line 1455 of yacc.c *\/ #line 793 \"ntp_parser.y\" { enqueue(cfgt.fudge, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 155: \/* Line 1455 of yacc.c *\/ #line 798 \"ntp_parser.y\" { enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 156: \/* Line 1455 of yacc.c *\/ #line 800 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 157: \/* Line 1455 of yacc.c *\/ #line 804 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 158: \/* Line 1455 of yacc.c *\/ #line 805 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 159: \/* Line 1455 of yacc.c *\/ #line 806 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 160: \/* Line 1455 of yacc.c *\/ #line 807 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 161: \/* Line 1455 of yacc.c *\/ #line 808 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 162: \/* Line 1455 of yacc.c *\/ #line 809 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 163: \/* Line 1455 of yacc.c *\/ #line 810 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 164: \/* Line 1455 of yacc.c *\/ #line 811 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 165: \/* Line 1455 of yacc.c *\/ #line 820 \"ntp_parser.y\" { append_queue(cfgt.enable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 166: \/* Line 1455 of yacc.c *\/ #line 822 \"ntp_parser.y\" { append_queue(cfgt.disable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 167: \/* Line 1455 of yacc.c *\/ #line 827 \"ntp_parser.y\" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 168: \/* Line 1455 of yacc.c *\/ #line 834 \"ntp_parser.y\" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 169: \/* Line 1455 of yacc.c *\/ #line 843 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 170: \/* Line 1455 of yacc.c *\/ #line 844 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 171: \/* Line 1455 of yacc.c *\/ #line 845 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 172: \/* Line 1455 of yacc.c *\/ #line 846 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 173: \/* Line 1455 of yacc.c *\/ #line 847 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 174: \/* Line 1455 of yacc.c *\/ #line 848 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 175: \/* Line 1455 of yacc.c *\/ #line 850 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror(\"enable\/disable stats remote configuration ignored\"); } } break; case 176: \/* Line 1455 of yacc.c *\/ #line 865 \"ntp_parser.y\" { append_queue(cfgt.tinker, (yyvsp[(2) - (2)].Queue)); } break; case 177: \/* Line 1455 of yacc.c *\/ #line 869 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 178: \/* Line 1455 of yacc.c *\/ #line 870 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 179: \/* Line 1455 of yacc.c *\/ #line 874 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 180: \/* Line 1455 of yacc.c *\/ #line 875 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 181: \/* Line 1455 of yacc.c *\/ #line 876 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 182: \/* Line 1455 of yacc.c *\/ #line 877 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 183: \/* Line 1455 of yacc.c *\/ #line 878 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 184: \/* Line 1455 of yacc.c *\/ #line 879 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 185: \/* Line 1455 of yacc.c *\/ #line 880 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 187: \/* Line 1455 of yacc.c *\/ #line 891 \"ntp_parser.y\" { if (curr_include_level >= MAXINCLUDELEVEL) { fprintf(stderr, \"getconfig: Maximum include file level exceeded.\\n\"); msyslog(LOG_ERR, \"getconfig: Maximum include file level exceeded.\"); } else { fp[curr_include_level + 1] = F_OPEN(FindConfig((yyvsp[(2) - (3)].String)), \"r\"); if (fp[curr_include_level + 1] == NULL) { fprintf(stderr, \"getconfig: Couldn't open <%s>\\n\", FindConfig((yyvsp[(2) - (3)].String))); msyslog(LOG_ERR, \"getconfig: Couldn't open <%s>\", FindConfig((yyvsp[(2) - (3)].String))); } else ip_file = fp[++curr_include_level]; } } break; case 188: \/* Line 1455 of yacc.c *\/ #line 907 \"ntp_parser.y\" { while (curr_include_level != -1) FCLOSE(fp[curr_include_level--]); } break; case 189: \/* Line 1455 of yacc.c *\/ #line 913 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 190: \/* Line 1455 of yacc.c *\/ #line 915 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 191: \/* Line 1455 of yacc.c *\/ #line 917 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 192: \/* Line 1455 of yacc.c *\/ #line 919 \"ntp_parser.y\" { \/* Null action, possibly all null parms *\/ } break; case 193: \/* Line 1455 of yacc.c *\/ #line 921 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 194: \/* Line 1455 of yacc.c *\/ #line 924 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 195: \/* Line 1455 of yacc.c *\/ #line 926 \"ntp_parser.y\" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror(\"logfile remote configuration ignored\"); } } break; case 196: \/* Line 1455 of yacc.c *\/ #line 937 \"ntp_parser.y\" { append_queue(cfgt.logconfig, (yyvsp[(2) - (2)].Queue)); } break; case 197: \/* Line 1455 of yacc.c *\/ #line 939 \"ntp_parser.y\" { append_queue(cfgt.phone, (yyvsp[(2) - (2)].Queue)); } break; case 198: \/* Line 1455 of yacc.c *\/ #line 941 \"ntp_parser.y\" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror(\"saveconfigdir remote configuration ignored\"); } } break; case 199: \/* Line 1455 of yacc.c *\/ #line 951 \"ntp_parser.y\" { enqueue(cfgt.setvar, (yyvsp[(2) - (2)].Set_var)); } break; case 200: \/* Line 1455 of yacc.c *\/ #line 953 \"ntp_parser.y\" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (2)].Address_node), NULL)); } break; case 201: \/* Line 1455 of yacc.c *\/ #line 955 \"ntp_parser.y\" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 202: \/* Line 1455 of yacc.c *\/ #line 957 \"ntp_parser.y\" { append_queue(cfgt.ttl, (yyvsp[(2) - (2)].Queue)); } break; case 203: \/* Line 1455 of yacc.c *\/ #line 959 \"ntp_parser.y\" { enqueue(cfgt.qos, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 204: \/* Line 1455 of yacc.c *\/ #line 964 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (1)].String))); } break; case 205: \/* Line 1455 of yacc.c *\/ #line 966 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_dval(T_WanderThreshold, (yyvsp[(2) - (2)].Double))); enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (2)].String))); } break; case 206: \/* Line 1455 of yacc.c *\/ #line 969 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, \"\\0\")); } break; case 207: \/* Line 1455 of yacc.c *\/ #line 974 \"ntp_parser.y\" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (4)].String), (yyvsp[(3) - (4)].String), (yyvsp[(4) - (4)].Integer)); } break; case 208: \/* Line 1455 of yacc.c *\/ #line 976 \"ntp_parser.y\" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (3)].String), (yyvsp[(3) - (3)].String), 0); } break; case 209: \/* Line 1455 of yacc.c *\/ #line 981 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 210: \/* Line 1455 of yacc.c *\/ #line 982 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 211: \/* Line 1455 of yacc.c *\/ #line 986 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 212: \/* Line 1455 of yacc.c *\/ #line 987 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_pval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node)); } break; case 213: \/* Line 1455 of yacc.c *\/ #line 991 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 214: \/* Line 1455 of yacc.c *\/ #line 992 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 215: \/* Line 1455 of yacc.c *\/ #line 997 \"ntp_parser.y\" { char prefix = (yyvsp[(1) - (1)].String)[0]; char *type = (yyvsp[(1) - (1)].String) + 1; if (prefix != '+' && prefix != '-' && prefix != '=') { yyerror(\"Logconfig prefix is not '+', '-' or '='\\n\"); } else (yyval.Attr_val) = create_attr_sval(prefix, estrdup(type)); YYFREE((yyvsp[(1) - (1)].String)); } break; case 216: \/* Line 1455 of yacc.c *\/ #line 1012 \"ntp_parser.y\" { enqueue(cfgt.nic_rules, create_nic_rule_node((yyvsp[(3) - (3)].Integer), NULL, (yyvsp[(2) - (3)].Integer))); } break; case 217: \/* Line 1455 of yacc.c *\/ #line 1017 \"ntp_parser.y\" { enqueue(cfgt.nic_rules, create_nic_rule_node(0, (yyvsp[(3) - (3)].String), (yyvsp[(2) - (3)].Integer))); } break; case 227: \/* Line 1455 of yacc.c *\/ #line 1048 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 228: \/* Line 1455 of yacc.c *\/ #line 1049 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 229: \/* Line 1455 of yacc.c *\/ #line 1054 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 230: \/* Line 1455 of yacc.c *\/ #line 1056 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 231: \/* Line 1455 of yacc.c *\/ #line 1061 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival('i', (yyvsp[(1) - (1)].Integer)); } break; case 233: \/* Line 1455 of yacc.c *\/ #line 1067 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_shorts('-', (yyvsp[(2) - (5)].Integer), (yyvsp[(4) - (5)].Integer)); } break; case 234: \/* Line 1455 of yacc.c *\/ #line 1071 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_pval((yyvsp[(2) - (2)].String))); } break; case 235: \/* Line 1455 of yacc.c *\/ #line 1072 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue(create_pval((yyvsp[(1) - (1)].String))); } break; case 236: \/* Line 1455 of yacc.c *\/ #line 1076 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Address_node)); } break; case 237: \/* Line 1455 of yacc.c *\/ #line 1077 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Address_node)); } break; case 238: \/* Line 1455 of yacc.c *\/ #line 1082 \"ntp_parser.y\" { if ((yyvsp[(1) - (1)].Integer) != 0 && (yyvsp[(1) - (1)].Integer) != 1) { yyerror(\"Integer value is not boolean (0 or 1). Assuming 1\"); (yyval.Integer) = 1; } else (yyval.Integer) = (yyvsp[(1) - (1)].Integer); } break; case 239: \/* Line 1455 of yacc.c *\/ #line 1090 \"ntp_parser.y\" { (yyval.Integer) = 1; } break; case 240: \/* Line 1455 of yacc.c *\/ #line 1091 \"ntp_parser.y\" { (yyval.Integer) = 0; } break; case 241: \/* Line 1455 of yacc.c *\/ #line 1095 \"ntp_parser.y\" { (yyval.Double) = (double)(yyvsp[(1) - (1)].Integer); } break; case 243: \/* Line 1455 of yacc.c *\/ #line 1106 \"ntp_parser.y\" { cfgt.sim_details = create_sim_node((yyvsp[(3) - (5)].Queue), (yyvsp[(4) - (5)].Queue)); \/* Reset the old_config_style variable *\/ old_config_style = 1; } break; case 244: \/* Line 1455 of yacc.c *\/ #line 1120 \"ntp_parser.y\" { old_config_style = 0; } break; case 245: \/* Line 1455 of yacc.c *\/ #line 1124 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 246: \/* Line 1455 of yacc.c *\/ #line 1125 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 247: \/* Line 1455 of yacc.c *\/ #line 1129 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 248: \/* Line 1455 of yacc.c *\/ #line 1130 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 249: \/* Line 1455 of yacc.c *\/ #line 1134 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_server)); } break; case 250: \/* Line 1455 of yacc.c *\/ #line 1135 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_server)); } break; case 251: \/* Line 1455 of yacc.c *\/ #line 1140 \"ntp_parser.y\" { (yyval.Sim_server) = create_sim_server((yyvsp[(1) - (5)].Address_node), (yyvsp[(3) - (5)].Double), (yyvsp[(4) - (5)].Queue)); } break; case 252: \/* Line 1455 of yacc.c *\/ #line 1144 \"ntp_parser.y\" { (yyval.Double) = (yyvsp[(3) - (4)].Double); } break; case 253: \/* Line 1455 of yacc.c *\/ #line 1148 \"ntp_parser.y\" { (yyval.Address_node) = (yyvsp[(3) - (3)].Address_node); } break; case 254: \/* Line 1455 of yacc.c *\/ #line 1152 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_script)); } break; case 255: \/* Line 1455 of yacc.c *\/ #line 1153 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_script)); } break; case 256: \/* Line 1455 of yacc.c *\/ #line 1158 \"ntp_parser.y\" { (yyval.Sim_script) = create_sim_script_info((yyvsp[(3) - (6)].Double), (yyvsp[(5) - (6)].Queue)); } break; case 257: \/* Line 1455 of yacc.c *\/ #line 1162 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 258: \/* Line 1455 of yacc.c *\/ #line 1163 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 259: \/* Line 1455 of yacc.c *\/ #line 1168 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 260: \/* Line 1455 of yacc.c *\/ #line 1170 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 261: \/* Line 1455 of yacc.c *\/ #line 1172 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 262: \/* Line 1455 of yacc.c *\/ #line 1174 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 263: \/* Line 1455 of yacc.c *\/ #line 1176 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; \/* Line 1455 of yacc.c *\/ #line 3826 \"ntp_parser.c\" default: break; } YY_SYMBOL_PRINT (\"-> $$ =\", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; \/* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. *\/ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; \/*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*\/ yyerrlab: \/* If not already recovering from an error, report this error. *\/ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_(\"syntax error\")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_(\"syntax error\")); if (yysize != 0) goto yyexhaustedlab; } } #endif } if (yyerrstatus == 3) { \/* If just tried and failed to reuse lookahead token after an error, discard it. *\/ if (yychar <= YYEOF) { \/* Return failure if at end of input. *\/ if (yychar == YYEOF) YYABORT; } else { yydestruct (\"Error: discarding\", yytoken, &yylval); yychar = YYEMPTY; } } \/* Else will try to reuse lookahead token after shifting the error token. *\/ goto yyerrlab1; \/*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*\/ yyerrorlab: \/* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. *\/ if (\/*CONSTCOND*\/ 0) goto yyerrorlab; \/* Do not reclaim the symbols of the rule which action triggered this YYERROR. *\/ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; \/*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*\/ yyerrlab1: yyerrstatus = 3; \/* Each real token shifted decrements this. *\/ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } \/* Pop the current state because it cannot handle the error token. *\/ if (yyssp == yyss) YYABORT; yydestruct (\"Error: popping\", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; \/* Shift the error token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; \/*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*\/ yyacceptlab: yyresult = 0; goto yyreturn; \/*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*\/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE \/*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*\/ yyexhaustedlab: yyerror (YY_(\"memory exhausted\")); yyresult = 2; \/* Fall through. *\/ #endif yyreturn: if (yychar != YYEMPTY) yydestruct (\"Cleanup: discarding lookahead\", yytoken, &yylval); \/* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. *\/ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct (\"Cleanup: popping\", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif \/* Make sure YYID is used. *\/ return YYID (yyresult); }","output":{"is_vulnerable":"True","vulnerability_types":["Improper Input Validation"],"explanation":"The log_config_command function in ntp_parser.y in ntpd in NTP before 4.2.7p42 allows remote attackers to cause a denial of service (ntpd crash) via crafted logconfig commands.","severity_level":"Medium","cwe":"CWE-20","cve":"CVE-2015-5194"}} -{"idx":158760,"input":"static long bcm_char_ioctl(struct file *filp, UINT cmd, ULONG arg) { struct bcm_tarang_data *pTarang = filp->private_data; void __user *argp = (void __user *)arg; struct bcm_mini_adapter *Adapter = pTarang->Adapter; INT Status = STATUS_FAILURE; int timeout = 0; struct bcm_ioctl_buffer IoBuffer; int bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Parameters Passed to control IOCTL cmd=0x%X arg=0x%lX\", cmd, arg); if (_IOC_TYPE(cmd) != BCM_IOCTL) return -EFAULT; if (_IOC_DIR(cmd) & _IOC_READ) Status = !access_ok(VERIFY_WRITE, argp, _IOC_SIZE(cmd)); else if (_IOC_DIR(cmd) & _IOC_WRITE) Status = !access_ok(VERIFY_READ, argp, _IOC_SIZE(cmd)); else if (_IOC_NONE == (_IOC_DIR(cmd) & _IOC_NONE)) Status = STATUS_SUCCESS; if (Status) return -EFAULT; if (Adapter->device_removed) return -EFAULT; if (FALSE == Adapter->fw_download_done) { switch (cmd) { case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: case IOCTL_BCM_GPIO_SET_REQUEST: case IOCTL_BCM_GPIO_STATUS_REQUEST: return -EACCES; default: break; } } Status = vendorextnIoctl(Adapter, cmd, arg); if (Status != CONTINUE_COMMON_PATH) return Status; switch (cmd) { \/* Rdms for Swin Idle... *\/ case IOCTL_BCM_REGISTER_READ_PRIVATE: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff; UINT Bufflen; u16 temp_value; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } Bufflen = IoBuffer.OutputLength; temp_value = 4 - (Bufflen % 4); Bufflen += temp_value % 4; temp_buff = kmalloc(Bufflen, GFP_KERNEL); if (!temp_buff) return -ENOMEM; bytes = rdmalt(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, Bufflen); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE_PRIVATE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; \/* Get WrmBuffer structure *\/ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); return -EFAULT; } Status = wrmalt(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Done\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Failed\\n\"); Status = -EFAULT; } break; } case IOCTL_BCM_REGISTER_READ: case IOCTL_BCM_EEPROM_REGISTER_READ: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff = NULL; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle Mode, Blocking Rdms\\n\"); return -EACCES; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } temp_buff = kmalloc(IoBuffer.OutputLength, GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; if ((((ULONG)sRdmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sRdmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM Done On invalid Address : %x Access Denied.\\n\", (int)sRdmBuffer.Register); kfree(temp_buff); return -EINVAL; } uiTempVar = sRdmBuffer.Register & EEPROM_REJECT_MASK; bytes = rdmaltWithLock(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, IoBuffer.OutputLength); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE: case IOCTL_BCM_EEPROM_REGISTER_WRITE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle Mode, Blocking Wrms\\n\"); return -EACCES; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; \/* Get WrmBuffer structure *\/ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if ((((ULONG)sWrmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sWrmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Done On invalid Address : %x Access Denied.\\n\", (int)sWrmBuffer.Register); return -EINVAL; } uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); return -EFAULT; } Status = wrmaltWithLock(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sWrmBuffer.Length); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, \"WRM Done\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Failed\\n\"); Status = -EFAULT; } break; } case IOCTL_BCM_GPIO_SET_REQUEST: { UCHAR ucResetValue[4]; UINT value = 0; UINT uiBit = 0; UINT uiOperation = 0; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO Can't be set\/clear in Low power Mode\"); return -EACCES; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; uiOperation = gpio_info.uiGpioValue; value = (1< is not correspond to LED !!!\", value); Status = -EINVAL; break; } \/* Set - setting 1 *\/ if (uiOperation) { \/* Set the gpio output register *\/ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Set the GPIO bit\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Failed to set the %dth GPIO\\n\", uiBit); break; } } else { \/* Set the gpio output register *\/ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Set the GPIO bit\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Failed to clear the %dth GPIO\\n\", uiBit); break; } } bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO_MODE_REGISTER read failed\"); break; } else { Status = STATUS_SUCCESS; } \/* Set the gpio mode register to output *\/ *(UINT *)ucResetValue |= (1<IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO Can't be set\/clear in Low power Mode\"); Status = -EACCES; break; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(threadReq)) return -EINVAL; if (copy_from_user(&threadReq, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; \/* if LED thread is running(Actively or Inactively) set it state to make inactive *\/ if (Adapter->LEDInfo.led_thread_running) { if (threadReq.ThreadState == LED_THREAD_ACTIVATION_REQ) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Activating thread req\"); Adapter->DriverState = LED_THREAD_ACTIVE; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DeActivating Thread req.....\"); Adapter->DriverState = LED_THREAD_INACTIVE; } \/* signal thread. *\/ wake_up(&Adapter->LEDInfo.notify_led_event); } } break; case IOCTL_BCM_GPIO_STATUS_REQUEST: { ULONG uiBit = 0; UCHAR ucRead[4]; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EACCES; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; \/* Set the gpio output register *\/ bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucRead, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM Failed\\n\"); return Status; } else { Status = STATUS_SUCCESS; } } break; case IOCTL_BCM_GPIO_MULTI_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_info gpio_multi_info[MAX_IDX]; struct bcm_gpio_multi_info *pgpio_multi_info = (struct bcm_gpio_multi_info *)gpio_multi_info; memset(pgpio_multi_info, 0, MAX_IDX * sizeof(struct bcm_gpio_multi_info)); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_info)) return -EINVAL; if (copy_from_user(&gpio_multi_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_info[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!\", pgpio_multi_info[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } \/* Set the gpio output register *\/ if ((pgpio_multi_info[WIMAX_IDX].uiGPIOMask) & (pgpio_multi_info[WIMAX_IDX].uiGPIOCommand)) { \/* Set 1's in GPIO OUTPUT REGISTER *\/ *(UINT *)ucResetValue = pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & pgpio_multi_info[WIMAX_IDX].uiGPIOValue; if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to BCM_GPIO_OUTPUT_SET_REG Failed.\"); return Status; } \/* Clear to 0's in GPIO OUTPUT REGISTER *\/ *(UINT *)ucResetValue = (pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & (~(pgpio_multi_info[WIMAX_IDX].uiGPIOValue))); if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to BCM_GPIO_OUTPUT_CLR_REG Failed.\"); return Status; } } if (pgpio_multi_info[WIMAX_IDX].uiGPIOMask) { bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM to GPIO_PIN_STATE_REGISTER Failed.\"); return Status; } else { Status = STATUS_SUCCESS; } pgpio_multi_info[WIMAX_IDX].uiGPIOValue = (*(UINT *)ucResetValue & pgpio_multi_info[WIMAX_IDX].uiGPIOMask); } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_info, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed while copying Content to IOBufer for user space err:%d\", Status); return -EFAULT; } } break; case IOCTL_BCM_GPIO_MODE_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_mode gpio_multi_mode[MAX_IDX]; struct bcm_gpio_multi_mode *pgpio_multi_mode = (struct bcm_gpio_multi_mode *)gpio_multi_mode; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_mode)) return -EINVAL; if (copy_from_user(&gpio_multi_mode, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Read of GPIO_MODE_REGISTER failed\"); return Status; } else { Status = STATUS_SUCCESS; } \/* Validating the request *\/ if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!\", pgpio_multi_mode[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } if (pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) { \/* write all OUT's (1's) *\/ *(UINT *) ucResetValue |= (pgpio_multi_mode[WIMAX_IDX].uiGPIOMode & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); \/* write all IN's (0's) *\/ *(UINT *) ucResetValue &= ~((~pgpio_multi_mode[WIMAX_IDX].uiGPIOMode) & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); \/* Currently implemented return the modes of all GPIO's * else needs to bit AND with mask *\/ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM to GPIO_MODE_REGISTER Done\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to GPIO_MODE_REGISTER Failed\"); Status = -EFAULT; break; } } else { \/* if uiGPIOMask is 0 then return mode register configuration *\/ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_mode, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed while copying Content to IOBufer for user space err:%d\", Status); return -EFAULT; } } break; case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: { PVOID pvBuffer = NULL; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(struct bcm_link_request)) return -EINVAL; if (IoBuffer.InputLength > MAX_CNTL_PKT_SIZE) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); down(&Adapter->LowPowerModeSync); Status = wait_event_interruptible_timeout(Adapter->lowpower_mode_wait_queue, !Adapter->bPreparingForLowPowerMode, (1 * HZ)); if (Status == -ERESTARTSYS) goto cntrlEnd; if (Adapter->bPreparingForLowPowerMode) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Preparing Idle Mode is still True - Hence Rejecting control message\\n\"); Status = STATUS_FAILURE; goto cntrlEnd; } Status = CopyBufferToControlPacket(Adapter, (PVOID)pvBuffer); cntrlEnd: up(&Adapter->LowPowerModeSync); kfree(pvBuffer); break; } case IOCTL_BCM_BUFFER_DOWNLOAD_START: { if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read\/Write is in progress\\n\"); return -EACCES; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Starting the firmware download PID =0x%x!!!!\\n\", current->pid); if (down_trylock(&Adapter->fw_download_sema)) return -EBUSY; Adapter->bBinDownloaded = FALSE; Adapter->fw_download_process_pid = current->pid; Adapter->bCfgDownloaded = FALSE; Adapter->fw_download_done = FALSE; netif_carrier_off(Adapter->dev); netif_stop_queue(Adapter->dev); Status = reset_card_proc(Adapter); if (Status) { pr_err(PFX \"%s: reset_card_proc Failed!\\n\", Adapter->dev->name); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } mdelay(10); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD: { struct bcm_firmware_info *psFwInfo = NULL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Starting the firmware download PID =0x%x!!!!\\n\", current->pid); if (!down_trylock(&Adapter->fw_download_sema)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Invalid way to download buffer. Use Start and then call this!!!\\n\"); up(&Adapter->fw_download_sema); Status = -EINVAL; return Status; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { up(&Adapter->fw_download_sema); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Length for FW DLD is : %lx\\n\", IoBuffer.InputLength); if (IoBuffer.InputLength > sizeof(struct bcm_firmware_info)) { up(&Adapter->fw_download_sema); return -EINVAL; } psFwInfo = kmalloc(sizeof(*psFwInfo), GFP_KERNEL); if (!psFwInfo) { up(&Adapter->fw_download_sema); return -ENOMEM; } if (copy_from_user(psFwInfo, IoBuffer.InputBuffer, IoBuffer.InputLength)) { up(&Adapter->fw_download_sema); kfree(psFwInfo); return -EFAULT; } if (!psFwInfo->pvMappedFirmwareAddress || (psFwInfo->u32FirmwareLength == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Something else is wrong %lu\\n\", psFwInfo->u32FirmwareLength); up(&Adapter->fw_download_sema); kfree(psFwInfo); Status = -EINVAL; return Status; } Status = bcm_ioctl_fw_download(Adapter, psFwInfo); if (Status != STATUS_SUCCESS) { if (psFwInfo->u32StartingAddress == CONFIG_BEGIN_ADDR) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL: Configuration File Upload Failed\\n\"); else BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL: Firmware File Upload Failed\\n\"); \/* up(&Adapter->fw_download_sema); *\/ if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = DRIVER_INIT; Adapter->LEDInfo.bLedInitDone = FALSE; wake_up(&Adapter->LEDInfo.notify_led_event); } } if (Status != STATUS_SUCCESS) up(&Adapter->fw_download_sema); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, \"IOCTL: Firmware File Uploaded\\n\"); kfree(psFwInfo); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD_STOP: { if (!down_trylock(&Adapter->fw_download_sema)) { up(&Adapter->fw_download_sema); return -EINVAL; } if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"FW download blocked as EEPROM Read\/Write is in progress\\n\"); up(&Adapter->fw_download_sema); return -EACCES; } Adapter->bBinDownloaded = TRUE; Adapter->bCfgDownloaded = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->downloadDDR = 0; \/* setting the Mips to Run *\/ Status = run_card_proc(Adapter); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Firm Download Failed\\n\"); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Firm Download Over...\\n\"); } mdelay(10); \/* Wait for MailBox Interrupt *\/ if (StartInterruptUrb((struct bcm_interface_adapter *)Adapter->pvInterfaceAdapter)) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Unable to send interrupt...\\n\"); timeout = 5*HZ; Adapter->waiting_to_fw_download_done = FALSE; wait_event_timeout(Adapter->ioctl_fw_dnld_wait_queue, Adapter->waiting_to_fw_download_done, timeout); Adapter->fw_download_process_pid = INVALID_PID; Adapter->fw_download_done = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->PrevNumRecvDescs = 0; atomic_set(&Adapter->cntrlpktCnt, 0); Adapter->LinkUpStatus = 0; Adapter->LinkStatus = 0; if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = FW_DOWNLOAD_DONE; wake_up(&Adapter->LEDInfo.notify_led_event); } if (!timeout) Status = -ENODEV; up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BE_BUCKET_SIZE: Status = 0; if (get_user(Adapter->BEBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_RTPS_BUCKET_SIZE: Status = 0; if (get_user(Adapter->rtPSBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_CHIP_RESET: { INT NVMAccess = down_trylock(&Adapter->NVMRdmWrmLock); if (NVMAccess) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \" IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read\/Write is in progress\\n\"); return -EACCES; } down(&Adapter->RxAppControlQueuelock); Status = reset_card_proc(Adapter); flushAllAppQ(); up(&Adapter->RxAppControlQueuelock); up(&Adapter->NVMRdmWrmLock); ResetCounters(Adapter); break; } case IOCTL_QOS_THRESHOLD: { USHORT uiLoopIndex; Status = 0; for (uiLoopIndex = 0; uiLoopIndex < NO_OF_QUEUES; uiLoopIndex++) { if (get_user(Adapter->PackInfo[uiLoopIndex].uiThreshold, (unsigned long __user *)arg)) { Status = -EFAULT; break; } } break; } case IOCTL_DUMP_PACKET_INFO: DumpPackInfo(Adapter); DumpPhsRules(&Adapter->stBCMPhsContext); Status = STATUS_SUCCESS; break; case IOCTL_GET_PACK_INFO: if (copy_to_user(argp, &Adapter->PackInfo, sizeof(struct bcm_packet_info)*NO_OF_QUEUES)) return -EFAULT; Status = STATUS_SUCCESS; break; case IOCTL_BCM_SWITCH_TRANSFER_MODE: { UINT uiData = 0; if (copy_from_user(&uiData, argp, sizeof(UINT))) return -EFAULT; if (uiData) { \/* Allow All Packets *\/ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SWITCH_TRANSFER_MODE: ETH_PACKET_TUNNELING_MODE\\n\"); Adapter->TransferMode = ETH_PACKET_TUNNELING_MODE; } else { \/* Allow IP only Packets *\/ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SWITCH_TRANSFER_MODE: IP_PACKET_ONLY_MODE\\n\"); Adapter->TransferMode = IP_PACKET_ONLY_MODE; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_DRIVER_VERSION: { ulong len; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; len = min_t(ulong, IoBuffer.OutputLength, strlen(DRV_VERSION) + 1); if (copy_to_user(IoBuffer.OutputBuffer, DRV_VERSION, len)) return -EFAULT; Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_CURRENT_STATUS: { struct bcm_link_state link_state; \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"copy_from_user failed..\\n\"); return -EFAULT; } if (IoBuffer.OutputLength != sizeof(link_state)) { Status = -EINVAL; break; } memset(&link_state, 0, sizeof(link_state)); link_state.bIdleMode = Adapter->IdleMode; link_state.bShutdownMode = Adapter->bShutStatus; link_state.ucLinkStatus = Adapter->LinkStatus; if (copy_to_user(IoBuffer.OutputBuffer, &link_state, min_t(size_t, sizeof(link_state), IoBuffer.OutputLength))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy_to_user Failed..\\n\"); return -EFAULT; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_SET_MAC_TRACING: { UINT tracing_flag; \/* copy ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&tracing_flag, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if (tracing_flag) Adapter->pTarangs->MacTracingEnabled = TRUE; else Adapter->pTarangs->MacTracingEnabled = FALSE; break; } case IOCTL_BCM_GET_DSX_INDICATION: { ULONG ulSFId = 0; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_add_indication_alt)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Mismatch req: %lx needed is =0x%zx!!!\", IoBuffer.OutputLength, sizeof(struct bcm_add_indication_alt)); return -EINVAL; } if (copy_from_user(&ulSFId, IoBuffer.InputBuffer, sizeof(ulSFId))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Get DSX Data SF ID is =%lx\\n\", ulSFId); get_dsx_sf_data_to_application(Adapter, ulSFId, IoBuffer.OutputBuffer); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_GET_HOST_MIBS: { PVOID temp_buff; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_host_stats_mibs)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Length Check failed %lu %zd\\n\", IoBuffer.OutputLength, sizeof(struct bcm_host_stats_mibs)); return -EINVAL; } \/* FIXME: HOST_STATS are too big for kmalloc (122048)! *\/ temp_buff = kzalloc(sizeof(struct bcm_host_stats_mibs), GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; Status = ProcessGetHostMibs(Adapter, temp_buff); GetDroppedAppCntrlPktMibs(temp_buff, pTarang); if (Status != STATUS_FAILURE) if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, sizeof(struct bcm_host_stats_mibs))) { kfree(temp_buff); return -EFAULT; } kfree(temp_buff); break; } case IOCTL_BCM_WAKE_UP_DEVICE_FROM_IDLE: if ((FALSE == Adapter->bTriedToWakeUpFromlowPowerMode) && (TRUE == Adapter->IdleMode)) { Adapter->usIdleModePattern = ABORT_IDLE_MODE; Adapter->bWakeUpDevice = TRUE; wake_up(&Adapter->process_rx_cntrlpkt); } Status = STATUS_SUCCESS; break; case IOCTL_BCM_BULK_WRM: { struct bcm_bulk_wrm_buffer *pBulkBuffer; UINT uiTempVar = 0; PCHAR pvBuffer = NULL; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle\/Shutdown Mode, Blocking Wrms\\n\"); Status = -EACCES; break; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(ULONG) * 2) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); pBulkBuffer = (struct bcm_bulk_wrm_buffer *)pvBuffer; if (((ULONG)pBulkBuffer->Register & 0x0F000000) != 0x0F000000 || ((ULONG)pBulkBuffer->Register & 0x3)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Done On invalid Address : %x Access Denied.\\n\", (int)pBulkBuffer->Register); kfree(pvBuffer); Status = -EINVAL; break; } uiTempVar = pBulkBuffer->Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize)&VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { kfree(pvBuffer); BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); Status = -EFAULT; break; } if (pBulkBuffer->SwapEndian == FALSE) Status = wrmWithLock(Adapter, (UINT)pBulkBuffer->Register, (PCHAR)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); else Status = wrmaltWithLock(Adapter, (UINT)pBulkBuffer->Register, (PUINT)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); if (Status != STATUS_SUCCESS) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Failed\\n\"); kfree(pvBuffer); break; } case IOCTL_BCM_GET_NVM_SIZE: if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (Adapter->eNVMType == NVM_EEPROM || Adapter->eNVMType == NVM_FLASH) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiNVMDSDSize, sizeof(UINT))) return -EFAULT; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_CAL_INIT: { UINT uiSectorSize = 0 ; if (Adapter->eNVMType == NVM_FLASH) { if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&uiSectorSize, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if ((uiSectorSize < MIN_SECTOR_SIZE) || (uiSectorSize > MAX_SECTOR_SIZE)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if (IsFlash2x(Adapter)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if ((TRUE == Adapter->bShutStatus) || (TRUE == Adapter->IdleMode)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device is in Idle\/Shutdown Mode\\n\"); return -EACCES; } Adapter->uiSectorSize = uiSectorSize; BcmUpdateSectorSize(Adapter, Adapter->uiSectorSize); } } Status = STATUS_SUCCESS; } else { Status = STATUS_FAILURE; } } break; case IOCTL_BCM_SET_DEBUG: #ifdef DEBUG { struct bcm_user_debug_state sUserDebugState; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"In SET_DEBUG ioctl\\n\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&sUserDebugState, IoBuffer.InputBuffer, sizeof(struct bcm_user_debug_state))) return -EFAULT; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL_BCM_SET_DEBUG: OnOff=%d Type = 0x%x \", sUserDebugState.OnOff, sUserDebugState.Type); \/* sUserDebugState.Subtype <<= 1; *\/ sUserDebugState.Subtype = 1 << sUserDebugState.Subtype; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"actual Subtype=0x%x\\n\", sUserDebugState.Subtype); \/* Update new 'DebugState' in the Adapter *\/ Adapter->stDebugState.type |= sUserDebugState.Type; \/* Subtype: A bitmap of 32 bits for Subtype per Type. * Valid indexes in 'subtype' array: 1,2,4,8 * corresponding to valid Type values. Hence we can use the 'Type' field * as the index value, ignoring the array entries 0,3,5,6,7 ! *\/ if (sUserDebugState.OnOff) Adapter->stDebugState.subtype[sUserDebugState.Type] |= sUserDebugState.Subtype; else Adapter->stDebugState.subtype[sUserDebugState.Type] &= ~sUserDebugState.Subtype; BCM_SHOW_DEBUG_BITMAP(Adapter); } #endif break; case IOCTL_BCM_NVM_READ: case IOCTL_BCM_NVM_WRITE: { struct bcm_nvm_readwrite stNVMReadWrite; PUCHAR pReadData = NULL; ULONG ulDSDMagicNumInUsrBuff = 0; struct timeval tv0, tv1; memset(&tv0, 0, sizeof(struct timeval)); memset(&tv1, 0, sizeof(struct timeval)); if ((Adapter->eNVMType == NVM_FLASH) && (Adapter->uiFlashLayoutMajorVersion == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"The Flash Control Section is Corrupted. Hence Rejection on NVM Read\/Write\\n\"); return -EFAULT; } if (IsFlash2x(Adapter)) { if ((Adapter->eActiveDSD != DSD0) && (Adapter->eActiveDSD != DSD1) && (Adapter->eActiveDSD != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"No DSD is active..hence NVM Command is blocked\"); return STATUS_FAILURE; } } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&stNVMReadWrite, (IOCTL_BCM_NVM_READ == cmd) ? IoBuffer.OutputBuffer : IoBuffer.InputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; \/* * Deny the access if the offset crosses the cal area limit. *\/ if (stNVMReadWrite.uiNumBytes > Adapter->uiNVMDSDSize) return STATUS_FAILURE; if (stNVMReadWrite.uiOffset > Adapter->uiNVMDSDSize - stNVMReadWrite.uiNumBytes) { \/* BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,\"Can't allow access beyond NVM Size: 0x%x 0x%x\\n\", stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); *\/ return STATUS_FAILURE; } pReadData = memdup_user(stNVMReadWrite.pBuffer, stNVMReadWrite.uiNumBytes); if (IS_ERR(pReadData)) return PTR_ERR(pReadData); do_gettimeofday(&tv0); if (IOCTL_BCM_NVM_READ == cmd) { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Status = BeceemNVMRead(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } if (copy_to_user(stNVMReadWrite.pBuffer, pReadData, stNVMReadWrite.uiNumBytes)) { kfree(pReadData); return -EFAULT; } } else { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Adapter->bHeaderChangeAllowed = TRUE; if (IsFlash2x(Adapter)) { \/* * New Requirement:- * DSD section updation will be allowed in two case:- * 1. if DSD sig is present in DSD header means dongle is ok and updation is fruitfull * 2. if point 1 failes then user buff should have DSD sig. this point ensures that if dongle is * corrupted then user space program first modify the DSD header with valid DSD sig so * that this as well as further write may be worthwhile. * * This restriction has been put assuming that if DSD sig is corrupted, DSD * data won't be considered valid. *\/ Status = BcmFlash2xCorruptSig(Adapter, Adapter->eActiveDSD); if (Status != STATUS_SUCCESS) { if (((stNVMReadWrite.uiOffset + stNVMReadWrite.uiNumBytes) != Adapter->uiNVMDSDSize) || (stNVMReadWrite.uiNumBytes < SIGNATURE_SIZE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DSD Sig is present neither in Flash nor User provided Input..\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } ulDSDMagicNumInUsrBuff = ntohl(*(PUINT)(pReadData + stNVMReadWrite.uiNumBytes - SIGNATURE_SIZE)); if (ulDSDMagicNumInUsrBuff != DSD_IMAGE_MAGIC_NUMBER) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DSD Sig is present neither in Flash nor User provided Input..\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } } } Status = BeceemNVMWrite(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes, stNVMReadWrite.bVerify); if (IsFlash2x(Adapter)) BcmFlash2xWriteSig(Adapter, Adapter->eActiveDSD); Adapter->bHeaderChangeAllowed = FALSE; up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } } do_gettimeofday(&tv1); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \" timetaken by Write\/read :%ld msec\\n\", (tv1.tv_sec - tv0.tv_sec)*1000 + (tv1.tv_usec - tv0.tv_usec)\/1000); kfree(pReadData); return STATUS_SUCCESS; } case IOCTL_BCM_FLASH2X_SECTION_READ: { struct bcm_flash2x_readwrite sFlash2xRead = {0}; PUCHAR pReadBuff = NULL ; UINT NOB = 0; UINT BuffSize = 0; UINT ReadBytes = 0; UINT ReadOffset = 0; void __user *OutPutBuff; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_FLASH2X_SECTION_READ Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; \/* Reading FLASH 2.x READ structure *\/ if (copy_from_user(&sFlash2xRead, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.Section :%x\", sFlash2xRead.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.offset :%x\", sFlash2xRead.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.numOfBytes :%x\", sFlash2xRead.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.bVerify :%x\\n\", sFlash2xRead.bVerify); \/* This was internal to driver for raw read. now it has ben exposed to user space app. *\/ if (validateFlash2xReadWrite(Adapter, &sFlash2xRead) == FALSE) return STATUS_FAILURE; NOB = sFlash2xRead.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB; ReadOffset = sFlash2xRead.offset ; OutPutBuff = IoBuffer.OutputBuffer; pReadBuff = (PCHAR)kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory allocation failed for Flash 2.x Read Structure\"); return -ENOMEM; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EACCES; } while (NOB) { if (NOB > Adapter->uiSectorSize) ReadBytes = Adapter->uiSectorSize; else ReadBytes = NOB; \/* Reading the data from Flash 2.x *\/ Status = BcmFlash2xBulkRead(Adapter, (PUINT)pReadBuff, sFlash2xRead.Section, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Flash 2x read err with Status :%d\", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Copy to use failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes ; } } up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); } break; case IOCTL_BCM_FLASH2X_SECTION_WRITE: { struct bcm_flash2x_readwrite sFlash2xWrite = {0}; PUCHAR pWriteBuff; void __user *InputAddr; UINT NOB = 0; UINT BuffSize = 0; UINT WriteOffset = 0; UINT WriteBytes = 0; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } \/* First make this False so that we can enable the Sector Permission Check in BeceemFlashBulkWrite *\/ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_FLASH2X_SECTION_WRITE Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; \/* Reading FLASH 2.x READ structure *\/ if (copy_from_user(&sFlash2xWrite, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.Section :%x\", sFlash2xWrite.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.offset :%d\", sFlash2xWrite.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.numOfBytes :%x\", sFlash2xWrite.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.bVerify :%x\\n\", sFlash2xWrite.bVerify); if ((sFlash2xWrite.Section != VSA0) && (sFlash2xWrite.Section != VSA1) && (sFlash2xWrite.Section != VSA2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Only VSA write is allowed\"); return -EINVAL; } if (validateFlash2xReadWrite(Adapter, &sFlash2xWrite) == FALSE) return STATUS_FAILURE; InputAddr = sFlash2xWrite.pDataBuff; WriteOffset = sFlash2xWrite.offset; NOB = sFlash2xWrite.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB ; pWriteBuff = kmalloc(BuffSize, GFP_KERNEL); if (pWriteBuff == NULL) return -ENOMEM; \/* extracting the remainder of the given offset. *\/ WriteBytes = Adapter->uiSectorSize; if (WriteOffset % Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize - (WriteOffset % Adapter->uiSectorSize); if (NOB < WriteBytes) WriteBytes = NOB; down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EACCES; } BcmFlash2xCorruptSig(Adapter, sFlash2xWrite.Section); do { Status = copy_from_user(pWriteBuff, InputAddr, WriteBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy to user failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EFAULT; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pWriteBuff, WriteBytes); \/* Writing the data from Flash 2.x *\/ Status = BcmFlash2xBulkWrite(Adapter, (PUINT)pWriteBuff, sFlash2xWrite.Section, WriteOffset, WriteBytes, sFlash2xWrite.bVerify); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash 2x read err with Status :%d\", Status); break; } NOB = NOB - WriteBytes; if (NOB) { WriteOffset = WriteOffset + WriteBytes; InputAddr = InputAddr + WriteBytes; if (NOB > Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize; else WriteBytes = NOB; } } while (NOB > 0); BcmFlash2xWriteSig(Adapter, sFlash2xWrite.Section); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); } break; case IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP: { struct bcm_flash2x_bitmap *psFlash2xBitMap; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_flash2x_bitmap)) return -EINVAL; psFlash2xBitMap = kzalloc(sizeof(struct bcm_flash2x_bitmap), GFP_KERNEL); if (psFlash2xBitMap == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory is not available\"); return -ENOMEM; } \/* Reading the Flash Sectio Bit map *\/ down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(psFlash2xBitMap); return -EACCES; } BcmGetFlash2xSectionalBitMap(Adapter, psFlash2xBitMap); up(&Adapter->NVMRdmWrmLock); if (copy_to_user(IoBuffer.OutputBuffer, psFlash2xBitMap, sizeof(struct bcm_flash2x_bitmap))) { kfree(psFlash2xBitMap); return -EFAULT; } kfree(psFlash2xBitMap); } break; case IOCTL_BCM_SET_ACTIVE_SECTION: { enum bcm_flash2x_section_val eFlash2xSectionVal = 0; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SET_ACTIVE_SECTION Called\"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of flash section val failed\"); return -EFAULT; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Status = BcmSetActiveSection(Adapter, eFlash2xSectionVal); if (Status) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed to make it's priority Highest. Status %d\", Status); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_IDENTIFY_ACTIVE_SECTION: { \/* Right Now we are taking care of only DSD *\/ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_IDENTIFY_ACTIVE_SECTION called\"); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_COPY_SECTION: { struct bcm_flash2x_copy_section sCopySectStrut = {0}; Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_COPY_SECTION Called\"); Adapter->bAllDSDWriteAllow = FALSE; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed Status :%d\", Status); return -EFAULT; } Status = copy_from_user(&sCopySectStrut, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_copy_section)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of Copy_Section_Struct failed with Status :%d\", Status); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Source SEction :%x\", sCopySectStrut.SrcSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Destination SEction :%x\", sCopySectStrut.DstSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"offset :%x\", sCopySectStrut.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"NOB :%x\", sCopySectStrut.numOfBytes); if (IsSectionExistInFlash(Adapter, sCopySectStrut.SrcSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Source Section<%x> does not exixt in Flash \", sCopySectStrut.SrcSection); return -EINVAL; } if (IsSectionExistInFlash(Adapter, sCopySectStrut.DstSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Destinatio Section<%x> does not exixt in Flash \", sCopySectStrut.DstSection); return -EINVAL; } if (sCopySectStrut.SrcSection == sCopySectStrut.DstSection) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Source and Destination section should be different\"); return -EINVAL; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } if (sCopySectStrut.SrcSection == ISO_IMAGE1 || sCopySectStrut.SrcSection == ISO_IMAGE2) { if (IsNonCDLessDevice(Adapter)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device is Non-CDLess hence won't have ISO !!\"); Status = -EINVAL; } else if (sCopySectStrut.numOfBytes == 0) { Status = BcmCopyISO(Adapter, sCopySectStrut); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Partial Copy of ISO section is not Allowed..\"); Status = STATUS_FAILURE; } up(&Adapter->NVMRdmWrmLock); return Status; } Status = BcmCopySection(Adapter, sCopySectStrut.SrcSection, sCopySectStrut.DstSection, sCopySectStrut.offset, sCopySectStrut.numOfBytes); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_GET_FLASH_CS_INFO: { Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \" IOCTL_BCM_GET_FLASH_CS_INFO Called\"); Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Connected device does not have flash\"); Status = -EINVAL; break; } if (IsFlash2x(Adapter) == TRUE) { if (IoBuffer.OutputLength < sizeof(struct bcm_flash2x_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlash2xCSInfo, sizeof(struct bcm_flash2x_cs_info))) return -EFAULT; } else { if (IoBuffer.OutputLength < sizeof(struct bcm_flash_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlashCSInfo, sizeof(struct bcm_flash_cs_info))) return -EFAULT; } } break; case IOCTL_BCM_SELECT_DSD: { UINT SectOfset = 0; enum bcm_flash2x_section_val eFlash2xSectionVal; eFlash2xSectionVal = NO_SECTION_VAL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SELECT_DSD Called\"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of flash section val failed\"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Read Section :%d\", eFlash2xSectionVal); if ((eFlash2xSectionVal != DSD0) && (eFlash2xSectionVal != DSD1) && (eFlash2xSectionVal != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Passed section<%x> is not DSD section\", eFlash2xSectionVal); return STATUS_FAILURE; } SectOfset = BcmGetSectionValStartOffset(Adapter, eFlash2xSectionVal); if (SectOfset == INVALID_OFFSET) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Provided Section val <%d> does not exixt in Flash 2.x\", eFlash2xSectionVal); return -EINVAL; } Adapter->bAllDSDWriteAllow = TRUE; Adapter->ulFlashCalStart = SectOfset; Adapter->eActiveDSD = eFlash2xSectionVal; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_NVM_RAW_READ: { struct bcm_nvm_readwrite stNVMRead; INT NOB ; INT BuffSize ; INT ReadOffset = 0; UINT ReadBytes = 0 ; PUCHAR pReadBuff; void __user *OutPutBuff; if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"NVM TYPE is not Flash\"); return -EINVAL; } \/* Copy Ioctl Buffer structure *\/ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"copy_from_user 1 failed\\n\"); return -EFAULT; } if (copy_from_user(&stNVMRead, IoBuffer.OutputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; NOB = stNVMRead.uiNumBytes; \/* In Raw-Read max Buff size : 64MB *\/ if (NOB > DEFAULT_BUFF_SIZE) BuffSize = DEFAULT_BUFF_SIZE; else BuffSize = NOB; ReadOffset = stNVMRead.uiOffset; OutPutBuff = stNVMRead.pBuffer; pReadBuff = kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory allocation failed for Flash 2.x Read Structure\"); Status = -ENOMEM; break; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle\/Shutdown Mode\\n\"); kfree(pReadBuff); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Adapter->bFlashRawRead = TRUE; while (NOB) { if (NOB > DEFAULT_BUFF_SIZE) ReadBytes = DEFAULT_BUFF_SIZE; else ReadBytes = NOB; \/* Reading the data from Flash 2.x *\/ Status = BeceemNVMRead(Adapter, (PUINT)pReadBuff, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash 2x read err with Status :%d\", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy to use failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes; } } Adapter->bFlashRawRead = FALSE; up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); break; } case IOCTL_BCM_CNTRLMSG_MASK: { ULONG RxCntrlMsgBitMask = 0; \/* Copy Ioctl Buffer structure *\/ Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"copy of Ioctl buffer is failed from user space\"); return -EFAULT; } if (IoBuffer.InputLength != sizeof(unsigned long)) { Status = -EINVAL; break; } Status = copy_from_user(&RxCntrlMsgBitMask, IoBuffer.InputBuffer, IoBuffer.InputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"copy of control bit mask failed from user space\"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\n Got user defined cntrl msg bit mask :%lx\", RxCntrlMsgBitMask); pTarang->RxCntrlMsgBitMask = RxCntrlMsgBitMask; } break; case IOCTL_BCM_GET_DEVICE_DRIVER_INFO: { struct bcm_driver_info DevInfo; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Called IOCTL_BCM_GET_DEVICE_DRIVER_INFO\\n\"); memset(&DevInfo, 0, sizeof(DevInfo)); DevInfo.MaxRDMBufferSize = BUFFER_4K; DevInfo.u32DSDStartOffset = EEPROM_CALPARAM_START; DevInfo.u32RxAlignmentCorrection = 0; DevInfo.u32NVMType = Adapter->eNVMType; DevInfo.u32InterfaceType = BCM_USB; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(DevInfo)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, &DevInfo, sizeof(DevInfo))) return -EFAULT; } break; case IOCTL_BCM_TIME_SINCE_NET_ENTRY: { struct bcm_time_elapsed stTimeElapsedSinceNetEntry = {0}; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_TIME_SINCE_NET_ENTRY called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_time_elapsed)) return -EINVAL; stTimeElapsedSinceNetEntry.ul64TimeElapsedSinceNetEntry = get_seconds() - Adapter->liTimeSinceLastNetEntry; if (copy_to_user(IoBuffer.OutputBuffer, &stTimeElapsedSinceNetEntry, sizeof(struct bcm_time_elapsed))) return -EFAULT; } break; case IOCTL_CLOSE_NOTIFICATION: BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_CLOSE_NOTIFICATION\"); break; default: pr_info(DRV_NAME \": unknown ioctl cmd=%#x\\n\", cmd); Status = STATUS_FAILURE; break; } return Status; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":199989,"input":"static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define CFormat \"\/Filter [ \/%s ]\\n\" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \\ { \\ if (xref != (MagickOffsetType *) NULL) \\ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \\ ThrowWriterException((exception),(message)); \\ } DisableMSCWarning(4310) static const char XMPProfile[]= { \"\\n\" \"\\n\" \" \\n\" \" \\n\" \" %s<\/xap:ModifyDate>\\n\" \" %s<\/xap:CreateDate>\\n\" \" %s<\/xap:MetadataDate>\\n\" \" %s<\/xap:CreatorTool>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" application\/pdf<\/dc:format>\\n\" \" \\n\" \" \\n\" \" %s<\/rdf:li>\\n\" \" <\/rdf:Alt>\\n\" \" <\/dc:title>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf<\/xapMM:DocumentID>\\n\" \" uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb<\/xapMM:InstanceID>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" %s<\/pdf:Producer>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" 3<\/pdfaid:part>\\n\" \" B<\/pdfaid:conformance>\\n\" \" <\/rdf:Description>\\n\" \" <\/rdf:RDF>\\n\" \"<\/x:xmpmeta>\\n\" \"\\n\" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MagickPathExtent], buffer[MagickPathExtent], *escape, date[MagickPathExtent], **labels, page_geometry[MagickPathExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm utc_time; time_t seconds; unsigned char *pixels; \/* Open output image file. *\/ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); \/* Allocate X ref memory. *\/ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(xref,0,2048UL*sizeof(*xref)); \/* Write Info object. *\/ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->alpha_trait != UndefinedPixelTrait) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,\"icc\"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\\n'); } \/* Write Catalog object. *\/ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Pages %.20g 0 R\\n\", (double) object+1); else { (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Metadata %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Pages %.20g 0 R\\n\", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Type \/Catalog\"); option=GetImageOption(image_info,\"pdf:page-direction\"); if ((option != (const char *) NULL) && (LocaleCompare(option,\"right-to-left\") == 0)) (void) WriteBlobString(image,\"\/ViewerPreferences<<\/PageDirection\/R2L>>\\n\"); (void) WriteBlobString(image,\"\\n\"); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { char create_date[MagickPathExtent], modify_date[MagickPathExtent], timestamp[MagickPathExtent], xmp_profile[MagickPathExtent]; \/* Write XMP object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Subtype \/XML\\n\"); *modify_date='\\0'; value=GetImageProperty(image,\"date:modify\",exception); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MagickPathExtent); *create_date='\\0'; value=GetImageProperty(image,\"date:create\",exception); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MagickPathExtent); (void) FormatMagickTime(GetMagickTime(),MagickPathExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g\\n\", (double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Type \/Metadata\\n\"); (void) WriteBlobString(image,\">>\\nstream\\n\"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); } \/* Write Pages object. *\/ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/Pages\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Kids [ %.20g 0 R \", (double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; \/* Predict page object id's. *\/ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,\"icc\"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } (void) WriteBlobString(image,\"]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Count %.20g\\n\",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,\"icc\"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,exception) == MagickFalse) || (image->alpha_trait != UndefinedPixelTrait)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; \/* LZW compression is forbidden *\/ break; } case NoCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; \/* ASCII 85 compression is forbidden *\/ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Scale relative to dots-per-inch. *\/ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)\/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)\/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,\"PDF\") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry, MagickPathExtent); (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)\/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)\/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; \/* Write Page object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/Page\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Parent %.20g 0 R\\n\", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Resources <<\\n\"); labels=(char **) NULL; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent, \"\/Font << \/F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent, \"\/XObject << \/Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ProcSet %.20g 0 R >>\\n\", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width\/resolution.x, 72.0*media_info.height\/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/CropBox [0 0 %g %g]\\n\",72.0*media_info.width\/resolution.x, 72.0*media_info.height\/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Contents %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Thumb %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Contents object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); (void) WriteBlobString(image,\"q\\n\"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,\"BT\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/F%.20g %g Tf\\n\", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\", labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"ET\\n\"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MagickPathExtent, \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x, (double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Im%.20g Do\\n\",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"Q\\n\"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Procset object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageC\",MagickPathExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageB\",MagickPathExtent); else (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageI\",MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\" ]\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Font object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (labels != (char **) NULL) { (void) WriteBlobString(image,\"\/Type \/Font\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Type1\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/F%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/BaseFont \/Helvetica\\n\"); (void) WriteBlobString(image,\"\/Encoding \/MacRomanEncoding\\n\"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write XObject object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/XObject\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/Im%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"\/Filter [ \/CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/DecodeParms [ << \" \"\/K %s \/BlackIs1 false \/Columns %.20g \/Rows %.20g >> ]\\n\",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ColorSpace %.20g 0 R\\n\", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->alpha_trait != UndefinedPixelTrait) { (void) FormatLocaleString(buffer,MagickPathExtent,\"\/SMask %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runoffset encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed DirectColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { \/* Dump number of colors and colormap. *\/ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Colorspace object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); device=\"DeviceRGB\"; channels=0; if (image->colorspace == CMYKColorspace) { device=\"DeviceCMYK\"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { device=\"DeviceGray\"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device=\"DeviceRGB\"; channels=3; } profile=GetImageProfile(image,\"icc\"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"\/%s\\n\",device); else (void) FormatLocaleString(buffer,MagickPathExtent, \"[ \/Indexed \/%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; \/* Write ICC profile. *\/ (void) FormatLocaleString(buffer,MagickPathExtent, \"[\/ICCBased %.20g 0 R]\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n\/N %.20g\\n\" \"\/Filter \/ASCII85Decode\\n\/Length %.20g 0 R\\n\/Alternate \/%s\\n>>\\n\" \"stream\\n\",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"endstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Thumb object. *\/ SetGeometry(image,&geometry); (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception); if (tile_image == (Image *) NULL) return(MagickFalse); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"\/Filter [ \/CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/DecodeParms [ << \" \"\/K %s \/BlackIs1 false \/Columns %.20g \/Rows %.20g >> ]\\n\",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ColorSpace %.20g 0 R\\n\", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image, exception); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( tile_image,p))); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed DirectColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(tile_image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(tile_image,p))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } else { \/* Dump number of colors and colormap. *\/ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, \"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=(unsigned char) GetPixelIndex(tile_image,p); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(tile_image,p)); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,\">>\\n\"); else { \/* Write Colormap object. *\/ if (compression == NoCompression) (void) WriteBlobString(image,\"\/Filter [ \/ASCII85Decode ]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); continue; } (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write softmask object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (image->alpha_trait == UndefinedPixelTrait) (void) WriteBlobString(image,\">>\\n\"); else { (void) WriteBlobString(image,\"\/Type \/XObject\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/Ma%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\", (double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/ColorSpace \/DeviceGray\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/BitsPerComponent %d\\n\",(compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); \/* Write Metadata object. *\/ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { escape=EscapeParenthesis(basename); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Title (%s)\\n\", escape); escape=DestroyString(escape); } else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { unsigned char hex_digits[16]; hex_digits[0]='0'; hex_digits[1]='1'; hex_digits[2]='2'; hex_digits[3]='3'; hex_digits[4]='4'; hex_digits[5]='5'; hex_digits[6]='6'; hex_digits[7]='7'; hex_digits[8]='8'; hex_digits[9]='9'; hex_digits[10]='A'; hex_digits[11]='B'; hex_digits[12]='C'; hex_digits[13]='D'; hex_digits[14]='E'; hex_digits[15]='F'; (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Title > 4) & 0x0f]); (void) WriteBlobByte(image,hex_digits[utf16[i] & 0x0f]); } (void) FormatLocaleString(buffer,MagickPathExtent,\">\\n\"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=GetMagickTime(); GetMagickUTCtime(&seconds,&utc_time); (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\", utc_time.tm_year+1900,utc_time.tm_mon+1,utc_time.tm_mday, utc_time.tm_hour,utc_time.tm_min,utc_time.tm_sec); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/CreationDate (%s)\\n\", date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ModDate (%s)\\n\",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Producer (%s)\\n\",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Xref object. *\/ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,\"xref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"0000000000 65535 f \\n\"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"trailer\\n\"); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Size %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Info %.20g 0 R\\n\",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Root %.20g 0 R\\n\",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image,exception); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ID [<%s> <%s>]\\n\", GetImageProperty(image,\"signature\",exception), GetImageProperty(image,\"signature\",exception)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"startxref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"%%EOF\\n\"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }","output":{"is_vulnerable":"True","vulnerability_types":["Integer Overflow or Wraparound"],"explanation":"In RestoreMSCWarning() of \/coders\/pdf.c there are several areas where calls to GetPixelIndex() could result in values outside the range of representable for the unsigned char type. The patch casts the return value of GetPixelIndex() to ssize_t type to avoid this bug. This undefined behavior could be triggered when ImageMagick processes a crafted pdf file. Red Hat Product Security marked this as Low severity because although it could potentially lead to an impact to application availability, no specific impact was demonstrated in this case. This flaw affects ImageMagick versions prior to 7.0.9-0.","severity_level":"NoInfo","cwe":"CWE-190","cve":"CVE-2020-27771"}} -{"idx":476009,"input":"void CLASS adobe_coeff (const char *t_make, const char *t_model) { static const struct { const char *prefix; short t_black, t_maximum, trans[12]; } table[] = { { \"AgfaPhoto DC-833m\", 0, 0, \/* DJC *\/ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { \"Apple QuickTake\", 0, 0, \/* DJC *\/ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, { \"Canon EOS D2000\", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { \"Canon EOS D6000\", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { \"Canon EOS D30\", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { \"Canon EOS D60\", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { \"Canon EOS 5D Mark III\", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { \"Canon EOS 5D Mark II\", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { \"Canon EOS 5D\", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { \"Canon EOS 6D\", 0, 0x3c82, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { \"Canon EOS 7D\", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { \"Canon EOS 10D\", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { \"Canon EOS 20Da\", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { \"Canon EOS 20D\", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { \"Canon EOS 30D\", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { \"Canon EOS 40D\", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { \"Canon EOS 50D\", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { \"Canon EOS 60D\", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { \"Canon EOS 70D\", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { \"Canon EOS 100D\", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { \"Canon EOS 300D\", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { \"Canon EOS 350D\", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { \"Canon EOS 400D\", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { \"Canon EOS 450D\", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { \"Canon EOS 500D\", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { \"Canon EOS 550D\", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { \"Canon EOS 600D\", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { \"Canon EOS 650D\", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { \"Canon EOS 700D\", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { \"Canon EOS 1000D\", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { \"Canon EOS 1100D\", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { \"Canon EOS M\", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { \"Canon EOS-1Ds Mark III\", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { \"Canon EOS-1Ds Mark II\", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { \"Canon EOS-1D Mark IV\", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { \"Canon EOS-1D Mark III\", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { \"Canon EOS-1D Mark II N\", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { \"Canon EOS-1D Mark II\", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { \"Canon EOS-1DS\", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { \"Canon EOS-1D C\", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { \"Canon EOS-1D X\", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { \"Canon EOS-1D\", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { \"Canon EOS C500\", 853, 0, \/* DJC *\/ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, { \"Canon PowerShot A530\", 0, 0, { 0 } }, \/* don't want the A5 matrix *\/ { \"Canon PowerShot A50\", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { \"Canon PowerShot A5\", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { \"Canon PowerShot G10\", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { \"Canon PowerShot G11\", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { \"Canon PowerShot G12\", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { \"Canon PowerShot G15\", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { \"Canon PowerShot G16\", 0, 0, { 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } }, { \"Canon PowerShot G1 X\", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { \"Canon PowerShot G1\", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { \"Canon PowerShot G2\", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { \"Canon PowerShot G3\", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { \"Canon PowerShot G5\", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { \"Canon PowerShot G6\", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { \"Canon PowerShot G9\", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { \"Canon PowerShot Pro1\", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { \"Canon PowerShot Pro70\", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { \"Canon PowerShot Pro90\", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { \"Canon PowerShot S30\", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { \"Canon PowerShot S40\", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { \"Canon PowerShot S45\", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { \"Canon PowerShot S50\", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { \"Canon PowerShot S60\", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { \"Canon PowerShot S70\", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { \"Canon PowerShot S90\", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { \"Canon PowerShot S95\", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { \"Canon PowerShot S120\", 0, 0, \/* LibRaw *\/ { 10800,-4782,-628,-2057,10783,1176,-802,2091,4739 } }, { \"Canon PowerShot S110\", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { \"Canon PowerShot S100\", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { \"Canon PowerShot SX1 IS\", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { \"Canon PowerShot SX50 HS\", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { \"Canon PowerShot A3300\", 0, 0, \/* DJC *\/ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { \"Canon PowerShot A470\", 0, 0, \/* DJC *\/ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { \"Canon PowerShot A610\", 0, 0, \/* DJC *\/ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { \"Canon PowerShot A620\", 0, 0, \/* DJC *\/ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { \"Canon PowerShot A630\", 0, 0, \/* DJC *\/ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { \"Canon PowerShot A640\", 0, 0, \/* DJC *\/ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { \"Canon PowerShot A650\", 0, 0, \/* DJC *\/ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { \"Canon PowerShot A720\", 0, 0, \/* DJC *\/ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { \"Canon PowerShot S3 IS\", 0, 0, \/* DJC *\/ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { \"Canon PowerShot SX110 IS\", 0, 0, \/* DJC *\/ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { \"Canon PowerShot SX220\", 0, 0, \/* DJC *\/ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { \"Casio EX-S20\", 0, 0, \/* DJC *\/ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { \"Casio EX-Z750\", 0, 0, \/* DJC *\/ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { \"Casio EX-Z10\", 128, 0xfff, \/* DJC *\/ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { \"CINE 650\", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { \"CINE 660\", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { \"CINE\", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { \"Contax N Digital\", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { \"Epson R-D1\", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { \"Fujifilm E550\", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { \"Fujifilm E900\", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { \"Fujifilm F5\", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { \"Fujifilm F6\", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { \"Fujifilm F77\", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { \"Fujifilm F7\", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { \"Fujifilm F8\", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { \"Fujifilm S100FS\", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { \"Fujifilm S20Pro\", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { \"Fujifilm S20\", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { \"Fujifilm S2Pro\", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { \"Fujifilm S3Pro\", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { \"Fujifilm S5Pro\", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { \"Fujifilm S5000\", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { \"Fujifilm S5100\", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { \"Fujifilm S5500\", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { \"Fujifilm S5200\", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { \"Fujifilm S5600\", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { \"Fujifilm S6\", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { \"Fujifilm S7000\", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { \"Fujifilm S9000\", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { \"Fujifilm S9500\", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { \"Fujifilm S9100\", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { \"Fujifilm S9600\", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { \"Fujifilm SL1000\", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { \"Fujifilm IS-1\", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { \"Fujifilm IS Pro\", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { \"Fujifilm HS10 HS11\", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { \"Fujifilm HS2\", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { \"Fujifilm HS3\", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { \"Fujifilm HS50EXR\", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { \"Fujifilm F900EXR\", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { \"Fujifilm X100S\", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { \"Fujifilm X100\", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { \"Fujifilm X10\", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { \"Fujifilm X20\", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { \"Fujifilm X-Pro1\", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { \"Fujifilm X-A1\", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { \"Fujifilm X-E1\", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { \"Fujifilm X-E2\", 0, 0, { 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } }, { \"Fujifilm XF1\", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { \"Fujifilm X-M1\", 0, 0, { 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } }, { \"Fujifilm X-S1\", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { \"Fujifilm XQ1\", 0, 0, { 14305,-7365,-687,-3117,12383,432,-287,1660,4361 } }, { \"Hasselblad Lunar\", 128, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { \"Hasselblad Stellar\", 200, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { \"Imacon Ixpress\", 0, 0, \/* DJC *\/ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { \"Kodak NC2000\", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { \"Kodak DCS315C\", 8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { \"Kodak DCS330C\", 8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { \"Kodak DCS420\", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { \"Kodak DCS460\", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { \"Kodak EOSDCS1\", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { \"Kodak EOSDCS3B\", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { \"Kodak DCS520C\", 178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { \"Kodak DCS560C\", 177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { \"Kodak DCS620C\", 177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { \"Kodak DCS620X\", 176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { \"Kodak DCS660C\", 173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { \"Kodak DCS720X\", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { \"Kodak DCS760C\", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { \"Kodak DCS Pro SLR\", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { \"Kodak DCS Pro 14nx\", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { \"Kodak DCS Pro 14\", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { \"Kodak ProBack645\", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { \"Kodak ProBack\", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { \"Kodak P712\", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { \"Kodak P850\", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { \"Kodak P880\", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { \"Kodak EasyShare Z980\", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { \"Kodak EasyShare Z981\", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { \"Kodak EasyShare Z990\", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { \"Kodak EASYSHARE Z1015\", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { \"Leaf CMost\", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { \"Leaf Valeo 6\", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { \"Leaf Aptus 54S\", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { \"Leaf Aptus 65\", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { \"Leaf Aptus 75\", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { \"Leaf\", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { \"Mamiya ZD\", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { \"Micron 2010\", 110, 0, \/* DJC *\/ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { \"Minolta DiMAGE 5\", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { \"Minolta DiMAGE 7Hi\", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { \"Minolta DiMAGE 7\", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { \"Minolta DiMAGE A1\", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { \"Minolta DiMAGE A200\", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { \"Minolta DiMAGE A2\", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { \"Minolta DiMAGE Z2\", 0, 0, \/* DJC *\/ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { \"Minolta DYNAX 5\", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { \"Minolta DYNAX 7\", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { \"Motorola PIXL\", 0, 0, \/* DJC *\/ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { \"Nikon D100\", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { \"Nikon D1H\", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { \"Nikon D1X\", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { \"Nikon D1\", 0, 0, \/* multiplied by 2.218750, 1.0, 1.148438 *\/ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { \"Nikon D200\", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { \"Nikon D2H\", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { \"Nikon D2X\", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { \"Nikon D3000\", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { \"Nikon D3100\", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { \"Nikon D3200\", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { \"Nikon D300\", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { \"Nikon D3X\", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { \"Nikon D3S\", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { \"Nikon D3\", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { \"Nikon D40X\", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { \"Nikon D40\", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { \"Nikon D4\", 0, 0, { 10076,-4135,-659,-4586,13006,746,-1189,2107,6185 } }, { \"Nikon D5000\", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { \"Nikon D5100\", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { \"Nikon D5200\", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, {\"Nikon D5300\",0, 0, { 10645,-5086,-698,-4938,13608,761,-1107,1874,5312 } }, { \"Nikon D50\", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { \"Nikon D600\", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, {\"Nikon D610\",0, 0, { 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } }, { \"Nikon D60\", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { \"Nikon D7000\", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { \"Nikon D7100\", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { \"Nikon D700\", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { \"Nikon D70\", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { \"Nikon D800\", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { \"Nikon D80\", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { \"Nikon D90\", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, {\"Nikon Df\",0, 0, { 10076,-4135,-659,-4586,13006,746,-1189,2107,6185 } }, { \"Nikon E700\", 0, 0x3dd, \/* DJC *\/ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { \"Nikon E800\", 0, 0x3dd, \/* DJC *\/ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { \"Nikon E950\", 0, 0x3dd, \/* DJC *\/ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { \"Nikon E995\", 0, 0, \/* copied from E5000 *\/ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { \"Nikon E2100\", 0, 0, \/* copied from Z2, new white balance *\/ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711} }, { \"Nikon E2500\", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { \"Nikon E3200\", 0, 0, \/* DJC *\/ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { \"Nikon E4300\", 0, 0, \/* copied from Minolta DiMAGE Z2 *\/ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { \"Nikon E4500\", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { \"Nikon E5000\", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { \"Nikon E5400\", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { \"Nikon E5700\", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { \"Nikon E8400\", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { \"Nikon E8700\", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { \"Nikon E8800\", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { \"Nikon COOLPIX A\", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { \"Nikon COOLPIX P330\", 0, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { \"Nikon COOLPIX P6000\", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { \"Nikon COOLPIX P7000\", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { \"Nikon COOLPIX P7100\", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { \"Nikon COOLPIX P7700\", 200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { \"Nikon COOLPIX P7800\", 200, 0, { 13443,-6418,-673,-1309,10025,1131,-462,1827,4782 } }, { \"Nikon 1 V2\", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { \"Nikon 1 J3\", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { \"Nikon 1 AW1\", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { \"Nikon 1 \", 0, 0, { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { \"Olympus C5050\", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { \"Olympus C5060\", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { \"Olympus C7070\", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { \"Olympus C70\", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { \"Olympus C80\", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { \"Olympus E-10\", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { \"Olympus E-1\", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { \"Olympus E-20\", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { \"Olympus E-300\", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { \"Olympus E-330\", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { \"Olympus E-30\", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { \"Olympus E-3\", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { \"Olympus E-400\", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { \"Olympus E-410\", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { \"Olympus E-420\", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { \"Olympus E-450\", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { \"Olympus E-500\", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { \"Olympus E-510\", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { \"Olympus E-520\", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { \"Olympus E-5\", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { \"Olympus E-600\", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { \"Olympus E-620\", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { \"Olympus E-P1\", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { \"Olympus E-P2\", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { \"Olympus E-P3\", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { \"Olympus E-P5\", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { \"Olympus E-PL1s\", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { \"Olympus E-PL1\", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { \"Olympus E-PL2\", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { \"Olympus E-PL3\", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { \"Olympus E-PL5\", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { \"Olympus E-PL6\", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { \"Olympus E-PM1\", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { \"Olympus E-PM2\", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, {\"Olympus E-M1\", 0, 0, { 11663,-5527,-419,-1683,9915,1389,-582,1933,5016 } }, { \"Olympus E-M5\", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { \"Olympus SP350\", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { \"Olympus SP3\", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { \"Olympus SP500UZ\", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { \"Olympus SP510UZ\", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { \"Olympus SP550UZ\", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { \"Olympus SP560UZ\", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { \"Olympus SP570UZ\", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, {\"Olympus STYLUS1\",0, 0, { 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } }, { \"Olympus XZ-10\", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { \"Olympus XZ-1\", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { \"Olympus XZ-2\", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { \"OmniVision ov5647\", 0, 0, \/* DJC *\/ { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, { \"Pentax *ist DL2\", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { \"Pentax *ist DL\", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { \"Pentax *ist DS2\", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { \"Pentax *ist DS\", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { \"Pentax *ist D\", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { \"Pentax K10D\", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { \"Pentax K1\", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { \"Pentax K20D\", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { \"Pentax K200D\", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { \"Pentax K2000\", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { \"Pentax K-m\", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { \"Pentax K-x\", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { \"Pentax K-r\", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { \"Pentax K-3\", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { \"Pentax K-5 II\", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { \"Pentax K-5\", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { \"Pentax K-7\", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { \"Pentax MX-1\", 0, 0, { 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } }, { \"Pentax Q10\", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { \"Pentax 645D\", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { \"Panasonic DMC-FZ8\", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { \"Panasonic DMC-FZ18\", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { \"Panasonic DMC-FZ28\", 15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { \"Panasonic DMC-FZ30\", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { \"Panasonic DMC-FZ3\", 143, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { \"Panasonic DMC-FZ4\", 143, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { \"Panasonic DMC-FZ50\", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { \"Panasonic DMC-FZ7\", 144, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { \"Leica V-LUX1\", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { \"Panasonic DMC-L10\", 15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { \"Panasonic DMC-L1\", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { \"Leica DIGILUX 3\", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { \"Panasonic DMC-LC1\", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { \"Leica DIGILUX 2\", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { \"Panasonic DMC-LF1\", 143, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { \"Leica C (Typ 112)\", 143, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { \"Panasonic DMC-LX1\", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { \"Leica D-LUX2\", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { \"Panasonic DMC-LX2\", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { \"Leica D-LUX3\", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { \"Panasonic DMC-LX3\", 15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { \"Leica D-LUX 4\", 15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { \"Panasonic DMC-LX5\", 143, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { \"Leica D-LUX 5\", 143, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { \"Panasonic DMC-LX7\", 143, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { \"Leica D-LUX 6\", 143, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { \"Panasonic DMC-FZ100\", 143, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { \"Leica V-LUX 2\", 143, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { \"Panasonic DMC-FZ150\", 143, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { \"Leica V-LUX 3\", 143, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { \"Panasonic DMC-FZ200\", 143, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { \"Leica V-LUX 4\", 143, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { \"Panasonic DMC-FX150\", 15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { \"Panasonic DMC-G10\", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { \"Panasonic DMC-G1\", 15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { \"Panasonic DMC-G2\", 15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { \"Panasonic DMC-G3\", 143, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { \"Panasonic DMC-G5\", 143, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { \"Panasonic DMC-G6\", 142, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { \"Panasonic DMC-GF1\", 15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { \"Panasonic DMC-GF2\", 143, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { \"Panasonic DMC-GF3\", 143, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { \"Panasonic DMC-GF5\", 143, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { \"Panasonic DMC-GF6\", 143, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { \"Panasonic DMC-GH1\", 15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { \"Panasonic DMC-GH2\", 15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { \"Panasonic DMC-GH3\", 144, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { \"Panasonic DMC-GM1\", 143, 0, { 8977,-3976,-425,-3050,11095,1117,-1217,2563,4750 } }, { \"Panasonic DMC-GX1\", 143, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, {\"Panasonic DMC-GX7\",143,0, {7541,-2355,-591,-3163,10598,1894,-933,2109,5006}}, { \"Phase One H 20\", 0, 0, \/* DJC *\/ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { \"Phase One H 25\", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { \"Phase One P 2\", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { \"Phase One P 30\", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { \"Phase One P 45\", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { \"Phase One P40\", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { \"Phase One P65\", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { \"Red One\", 704, 0xffff, \/* DJC *\/ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { \"Samsung EK-GN120\", 0, 0, \/* Adobe; Galaxy NX *\/ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { \"Samsung EX1\", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { \"Samsung EX2F\", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { \"Samsung EK-GN120\", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { \"Samsung NX300\", 0, 0, { 8873,-3984,-372,-3759,12305,1013,-994,1981,4788 } }, { \"Samsung NX2000\", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { \"Samsung NX2\", 0, 0xfff, \/* NX20, NX200, NX210 *\/ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { \"Samsung NX1000\", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { \"Samsung NX1100\", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { \"Samsung NX\", 0, 0, \/* NX5, NX10, NX11, NX100 *\/ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { \"Samsung WB2000\", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { \"Samsung GX-1\", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { \"Samsung GX20\", 0, 0, \/* copied from Pentax K20D *\/ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { \"Samsung S85\", 0, 0, \/* DJC *\/ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, \/\/ Foveon: LibRaw color data { \"Sigma SD9\", 15, 4095, \/* LibRaw *\/ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, \/\/{ 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { \"Sigma SD10\", 15, 16383, \/* LibRaw *\/ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, \/\/{ 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { \"Sigma SD14\", 15, 16383, \/* LibRaw *\/ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, \/\/{ 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { \"Sigma SD15\", 15, 4095, \/* LibRaw *\/ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, \/\/{ 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, \/\/ Merills + SD1 { \"Sigma SD1\", 31, 4095, \/* LibRaw *\/ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { \"Sigma DP1 Merrill\", 31, 4095, \/* LibRaw *\/ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { \"Sigma DP2 Merrill\", 31, 4095, \/* LibRaw *\/ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { \"Sigma DP3 Merrill\", 31, 4095, \/* LibRaw *\/ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, \/\/ Sigma DP (non-Merill Versions) { \"Sigma DP\", 0, 4095, \/* LibRaw *\/ \/\/ { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { \"Sinar\", 0, 0, \/* DJC *\/ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { \"Sony DSC-F828\", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { \"Sony DSC-R1\", -512, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { \"Sony DSC-V3\", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, { \"Sony DSC-RX100M2\", -200, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { \"Sony DSC-RX100\", -200, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, {\"Sony DSC-RX10\",0, 0, { 8562,-3595,-385,-2715,11089,1128,-1023,2081,4400 } }, { \"Sony DSC-RX1R\", -128, 0, { 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } }, { \"Sony DSC-RX1\", -128, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { \"Sony DSLR-A100\", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { \"Sony DSLR-A290\", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { \"Sony DSLR-A2\", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { \"Sony DSLR-A300\", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { \"Sony DSLR-A330\", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { \"Sony DSLR-A350\", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { \"Sony DSLR-A380\", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { \"Sony DSLR-A390\", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { \"Sony DSLR-A450\", -128, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { \"Sony DSLR-A580\", -128, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { \"Sony DSLR-A5\", -128, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { \"Sony DSLR-A700\", -128, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { \"Sony DSLR-A850\", -128, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { \"Sony DSLR-A900\", -128, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, {\"Sony ILCE-3000\",-128, 0, { 14009,-8208,729,3738,4752,2932,5743,-3800,6494 } }, {\"Sony ILCE-A7R\",-128, 0, { 8592,-3219,-348,-3846,12042,1475,-1079,2166,5893 } }, {\"Sony ILCE-A7\",-128, 0, { 8592,-3219,-348,-3846,12042,1475,-1079,2166,5893 } }, { \"Sony NEX-5T\", -128, 0, { 7623,-2693,-347,-4060,11875,1928,-1363,2329,5752 } }, { \"Sony NEX-5N\", -128, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { \"Sony NEX-5R\", -128, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { \"Sony NEX-3N\", -128, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { \"Sony NEX-3\", -128, 0, \/* Adobe *\/ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { \"Sony NEX-5\", -128, 0, \/* Adobe *\/ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { \"Sony NEX-6\", -128, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { \"Sony NEX-7\", -128, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { \"Sony NEX\", -128, 0, \/* NEX-C3, NEX-F3 *\/ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { \"Sony SLT-A33\", -128, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { \"Sony SLT-A35\", -128, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { \"Sony SLT-A37\", -128, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { \"Sony SLT-A55\", -128, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { \"Sony SLT-A57\", -128, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { \"Sony SLT-A58\", -128, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { \"Sony SLT-A65\", -128, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { \"Sony SLT-A77\", -128, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { \"Sony SLT-A99\", -128, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; double cam_xyz[4][3]; char name[130]; int i, j; sprintf (name, \"%s %s\", t_make, t_model); for (i=0; i < sizeof table \/ sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if (table[i].t_black>0) black = (ushort) table[i].t_black; else if(table[i].t_black <0 && black == 0 ) black = (ushort) (-table[i].t_black); if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum; if (table[i].trans[0]) { for (raw_color = j=0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.cam_xyz[0][j] = #endif cam_xyz[0][j] = table[i].trans[j] \/ 10000.0; cam_xyz_coeff (rgb_cam, cam_xyz); } break; } }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":302460,"input":"STATIC regnode_offset S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth, const bool stop_at_1, \/* Just parse the next thing, don't look for a full character class *\/ bool allow_mutiple_chars, const bool silence_non_portable, \/* Don't output warnings about too large characters *\/ const bool strict, bool optimizable, \/* ? Allow a non-ANYOF return node *\/ SV** ret_invlist \/* Return an inversion list, not a node *\/ ) { \/* parse a bracketed class specification. Most of these will produce an * ANYOF node; but something like [a] will produce an EXACT node; [aA], an * EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex * under \/i with multi-character folds: it will be rewritten following the * paradigm of this example, where the s are characters which * fold to multiple character sequences: * \/[abc\\x{multi-fold1}def\\x{multi-fold2}ghi]\/i * gets effectively rewritten as: * \/(?:\\x{multi-fold1}|\\x{multi-fold2}|[abcdefghi]\/i * reg() gets called (recursively) on the rewritten version, and this * function will return what it constructs. (Actually the s * aren't physically removed from the [abcdefghi], it's just that they are * ignored in the recursion by means of a flag: * .) * * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS * characters, with the corresponding bit set if that character is in the * list. For characters above this, an inversion list is used. There * are extra bits for \\w, etc. in locale ANYOFs, as what these match is not * determinable at compile time * * On success, returns the offset at which any next node should be placed * into the regex engine program being compiled. * * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to * UTF-8 *\/ dVAR; UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE; IV range = 0; UV value = OOB_UNICODE, save_value = OOB_UNICODE; regnode_offset ret = -1; \/* Initialized to an illegal value *\/ STRLEN numlen; int namedclass = OOB_NAMEDCLASS; char *rangebegin = NULL; SV *listsv = NULL; \/* List of \\p{user-defined} whose definitions aren't available at the time this was called *\/ STRLEN initial_listsv_len = 0; \/* Kind of a kludge to see if it is more than just initialized. *\/ SV* properties = NULL; \/* Code points that match \\p{} \\P{} *\/ SV* posixes = NULL; \/* Code points that match classes like [:word:], extended beyond the Latin1 range. These have to be kept separate from other code points for much of this function because their handling is different under \/i, and for most classes under \/d as well *\/ SV* nposixes = NULL; \/* Similarly for [:^word:]. These are kept separate for a while from the non-complemented versions because of complications with \/d matching *\/ SV* simple_posixes = NULL; \/* But under some conditions, the classes can be treated more simply than the general case, leading to less compilation and execution work *\/ UV element_count = 0; \/* Number of distinct elements in the class. Optimizations may be possible if this is tiny *\/ AV * multi_char_matches = NULL; \/* Code points that fold to more than one character; used under \/i *\/ UV n; char * stop_ptr = RExC_end; \/* where to stop parsing *\/ \/* ignore unescaped whitespace? *\/ const bool skip_white = cBOOL( ret_invlist || (RExC_flags & RXf_PMf_EXTENDED_MORE)); \/* inversion list of code points this node matches only when the target * string is in UTF-8. These are all non-ASCII, < 256. (Because is under * \/d) *\/ SV* upper_latin1_only_utf8_matches = NULL; \/* Inversion list of code points this node matches regardless of things * like locale, folding, utf8ness of the target string *\/ SV* cp_list = NULL; \/* Like cp_list, but code points on this list need to be checked for things * that fold to\/from them under \/i *\/ SV* cp_foldable_list = NULL; \/* Like cp_list, but code points on this list are valid only when the * runtime locale is UTF-8 *\/ SV* only_utf8_locale_list = NULL; \/* In a range, if one of the endpoints is non-character-set portable, * meaning that it hard-codes a code point that may mean a different * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a * mnemonic '\\t' which each mean the same character no matter which * character set the platform is on. *\/ unsigned int non_portable_endpoint = 0; \/* Is the range unicode? which means on a platform that isn't 1-1 native * to Unicode (i.e. non-ASCII), each code point in it should be considered * to be a Unicode value. *\/ bool unicode_range = FALSE; bool invert = FALSE; \/* Is this class to be complemented *\/ bool warn_super = ALWAYS_WARN_SUPER; const char * orig_parse = RExC_parse; \/* This variable is used to mark where the end in the input is of something * that looks like a POSIX construct but isn't. During the parse, when * something looks like it could be such a construct is encountered, it is * checked for being one, but not if we've already checked this area of the * input. Only after this position is reached do we check again *\/ char *not_posix_region_end = RExC_parse - 1; AV* posix_warnings = NULL; const bool do_posix_warnings = ckWARN(WARN_REGEXP); U8 op = END; \/* The returned node-type, initialized to an impossible one. *\/ U8 anyof_flags = 0; \/* flag bits if the node is an ANYOF-type *\/ U32 posixl = 0; \/* bit field of posix classes matched under \/l *\/ \/* Flags as to what things aren't knowable until runtime. (Note that these are * mutually exclusive.) *\/ #define HAS_USER_DEFINED_PROPERTY 0x01 \/* \/u any user-defined properties that haven't been defined as of yet *\/ #define HAS_D_RUNTIME_DEPENDENCY 0x02 \/* \/d if the target being matched is UTF-8 or not *\/ #define HAS_L_RUNTIME_DEPENDENCY 0x04 \/* \/l what the posix classes match and what gets folded *\/ U32 has_runtime_dependency = 0; \/* OR of the above flags *\/ GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGCLASS; #ifndef DEBUGGING PERL_UNUSED_ARG(depth); #endif \/* If wants an inversion list returned, we can't optimize to something * else. *\/ if (ret_invlist) { optimizable = FALSE; } DEBUG_PARSE(\"clas\"); #if UNICODE_MAJOR_VERSION < 3 \/* no multifolds in early Unicode *\/ \\ || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \\ && UNICODE_DOT_DOT_VERSION == 0) allow_mutiple_chars = FALSE; #endif \/* We include the \/i status at the beginning of this so that we can * know it at runtime *\/ listsv = sv_2mortal(Perl_newSVpvf(aTHX_ \"#%d\\n\", cBOOL(FOLD))); initial_listsv_len = SvCUR(listsv); SvTEMP_off(listsv); \/* Grr, TEMPs and mortals are conflated. *\/ SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); assert(RExC_parse <= RExC_end); if (UCHARAT(RExC_parse) == '^') { \/* Complement the class *\/ RExC_parse++; invert = TRUE; allow_mutiple_chars = FALSE; MARK_NAUGHTY(1); SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); } \/* Check that they didn't say [:posix:] instead of [[:posix:]] *\/ if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) { int maybe_class = handle_possible_posix(pRExC_state, RExC_parse, ¬_posix_region_end, NULL, TRUE \/* checking only *\/); if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) { ckWARN4reg(not_posix_region_end, \"POSIX syntax [%c %c] belongs inside character classes%s\", *RExC_parse, *RExC_parse, (maybe_class == OOB_NAMEDCLASS) ? ((POSIXCC_NOTYET(*RExC_parse)) ? \" (but this one isn't implemented)\" : \" (but this one isn't fully valid)\") : \"\" ); } } \/* If the caller wants us to just parse a single element, accomplish this * by faking the loop ending condition *\/ if (stop_at_1 && RExC_end > RExC_parse) { stop_ptr = RExC_parse + 1; } \/* allow 1st char to be ']' (allowing it to be '-' is dealt with later) *\/ if (UCHARAT(RExC_parse) == ']') goto charclassloop; while (1) { if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0 && RExC_parse > not_posix_region_end) { \/* Warnings about posix class issues are considered tentative until * we are far enough along in the parse that we can no longer * change our mind, at which point we output them. This is done * each time through the loop so that a later class won't zap them * before they have been dealt with. *\/ output_posix_warnings(pRExC_state, posix_warnings); } if (RExC_parse >= stop_ptr) { break; } SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); if (UCHARAT(RExC_parse) == ']') { break; } charclassloop: namedclass = OOB_NAMEDCLASS; \/* initialize as illegal *\/ save_value = value; save_prevvalue = prevvalue; if (!range) { rangebegin = RExC_parse; element_count++; non_portable_endpoint = 0; } if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) { value = utf8n_to_uvchr((U8*)RExC_parse, RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT); RExC_parse += numlen; } else value = UCHARAT(RExC_parse++); if (value == '[') { char * posix_class_end; namedclass = handle_possible_posix(pRExC_state, RExC_parse, &posix_class_end, do_posix_warnings ? &posix_warnings : NULL, FALSE \/* die if error *\/); if (namedclass > OOB_NAMEDCLASS) { \/* If there was an earlier attempt to parse this particular * posix class, and it failed, it was a false alarm, as this * successful one proves *\/ if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0 && not_posix_region_end >= RExC_parse && not_posix_region_end <= posix_class_end) { av_undef(posix_warnings); } RExC_parse = posix_class_end; } else if (namedclass == OOB_NAMEDCLASS) { not_posix_region_end = posix_class_end; } else { namedclass = OOB_NAMEDCLASS; } } else if ( RExC_parse - 1 > not_posix_region_end && MAYBE_POSIXCC(value)) { (void) handle_possible_posix( pRExC_state, RExC_parse - 1, \/* -1 because parse has already been advanced *\/ ¬_posix_region_end, do_posix_warnings ? &posix_warnings : NULL, TRUE \/* checking only *\/); } else if ( strict && ! skip_white && ( _generic_isCC(value, _CC_VERTSPACE) || is_VERTWS_cp_high(value))) { vFAIL(\"Literal vertical space in [] is illegal except under \/x\"); } else if (value == '\\\\') { \/* Is a backslash; get the code point of the char after it *\/ if (RExC_parse >= RExC_end) { vFAIL(\"Unmatched [\"); } if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) { value = utf8n_to_uvchr((U8*)RExC_parse, RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT); RExC_parse += numlen; } else value = UCHARAT(RExC_parse++); \/* Some compilers cannot handle switching on 64-bit integer * values, therefore value cannot be an UV. Yes, this will * be a problem later if we want switch on Unicode. * A similar issue a little bit later when switching on * namedclass. --jhi *\/ \/* If the \\ is escaping white space when white space is being * skipped, it means that that white space is wanted literally, and * is already in 'value'. Otherwise, need to translate the escape * into what it signifies. *\/ if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) { case 'w': namedclass = ANYOF_WORDCHAR; break; case 'W': namedclass = ANYOF_NWORDCHAR; break; case 's': namedclass = ANYOF_SPACE; break; case 'S': namedclass = ANYOF_NSPACE; break; case 'd': namedclass = ANYOF_DIGIT; break; case 'D': namedclass = ANYOF_NDIGIT; break; case 'v': namedclass = ANYOF_VERTWS; break; case 'V': namedclass = ANYOF_NVERTWS; break; case 'h': namedclass = ANYOF_HORIZWS; break; case 'H': namedclass = ANYOF_NHORIZWS; break; case 'N': \/* Handle \\N{NAME} in class *\/ { const char * const backslash_N_beg = RExC_parse - 2; int cp_count; if (! grok_bslash_N(pRExC_state, NULL, \/* No regnode *\/ &value, \/* Yes single value *\/ &cp_count, \/* Multiple code pt count *\/ flagp, strict, depth) ) { if (*flagp & NEED_UTF8) FAIL(\"panic: grok_bslash_N set NEED_UTF8\"); RETURN_FAIL_ON_RESTART_FLAGP(flagp); if (cp_count < 0) { vFAIL(\"\\\\N in a character class must be a named character: \\\\N{...}\"); } else if (cp_count == 0) { ckWARNreg(RExC_parse, \"Ignoring zero length \\\\N{} in character class\"); } else { \/* cp_count > 1 *\/ assert(cp_count > 1); if (! RExC_in_multi_char_class) { if ( ! allow_mutiple_chars || invert || range || *RExC_parse == '-') { if (strict) { RExC_parse--; vFAIL(\"\\\\N{} in inverted character class or as a range end-point is restricted to one character\"); } ckWARNreg(RExC_parse, \"Using just the first character returned by \\\\N{} in character class\"); break; \/* contains the first code point. Drop out of the switch to process it *\/ } else { SV * multi_char_N = newSVpvn(backslash_N_beg, RExC_parse - backslash_N_beg); multi_char_matches = add_multi_match(multi_char_matches, multi_char_N, cp_count); } } } \/* End of cp_count != 1 *\/ \/* This element should not be processed further in this * class *\/ element_count--; value = save_value; prevvalue = save_prevvalue; continue; \/* Back to top of loop to get next char *\/ } \/* Here, is a single code point, and contains it *\/ unicode_range = TRUE; \/* \\N{} are Unicode *\/ } break; case 'p': case 'P': { char *e; \/* \\p means they want Unicode semantics *\/ REQUIRE_UNI_RULES(flagp, 0); if (RExC_parse >= RExC_end) vFAIL2(\"Empty \\\\%c\", (U8)value); if (*RExC_parse == '{') { const U8 c = (U8)value; e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse); if (!e) { RExC_parse++; vFAIL2(\"Missing right brace on \\\\%c{}\", c); } RExC_parse++; \/* White space is allowed adjacent to the braces and after * any '^', even when not under \/x *\/ while (isSPACE(*RExC_parse)) { RExC_parse++; } if (UCHARAT(RExC_parse) == '^') { \/* toggle. (The rhs xor gets the single bit that * differs between P and p; the other xor inverts just * that bit) *\/ value ^= 'P' ^ 'p'; RExC_parse++; while (isSPACE(*RExC_parse)) { RExC_parse++; } } if (e == RExC_parse) vFAIL2(\"Empty \\\\%c{}\", c); n = e - RExC_parse; while (isSPACE(*(RExC_parse + n - 1))) n--; } \/* The \\p isn't immediately followed by a '{' *\/ else if (! isALPHA(*RExC_parse)) { RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL2(\"Character following \\\\%c must be '{' or a \" \"single-character Unicode property name\", (U8) value); } else { e = RExC_parse; n = 1; } { char* name = RExC_parse; \/* Any message returned about expanding the definition *\/ SV* msg = newSVpvs_flags(\"\", SVs_TEMP); \/* If set TRUE, the property is user-defined as opposed to * official Unicode *\/ bool user_defined = FALSE; SV * prop_definition = parse_uniprop_string( name, n, UTF, FOLD, FALSE, \/* This is compile-time *\/ \/* We can't defer this defn when * the full result is required in * this call *\/ ! cBOOL(ret_invlist), &user_defined, msg, 0 \/* Base level *\/ ); if (SvCUR(msg)) { \/* Assumes any error causes a msg *\/ assert(prop_definition == NULL); RExC_parse = e + 1; if (SvUTF8(msg)) { \/* msg being UTF-8 makes the whole thing so, or else the display is mojibake *\/ RExC_utf8 = TRUE; } \/* diag_listed_as: Can't find Unicode property definition \"%s\" in regex; marked by <-- HERE in m\/%s\/ *\/ vFAIL2utf8f(\"%\" UTF8f, UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg))); } if (! is_invlist(prop_definition)) { \/* Here, the definition isn't known, so we have gotten * returned a string that will be evaluated if and when * encountered at runtime. We add it to the list of * such properties, along with whether it should be * complemented or not *\/ if (value == 'P') { sv_catpvs(listsv, \"!\"); } else { sv_catpvs(listsv, \"+\"); } sv_catsv(listsv, prop_definition); has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY; \/* We don't know yet what this matches, so have to flag * it *\/ anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP; } else { assert (prop_definition && is_invlist(prop_definition)); \/* Here we do have the complete property definition * * Temporary workaround for [perl #133136]. For this * precise input that is in the .t that is failing, * load utf8.pm, which is what the test wants, so that * that .t passes *\/ if ( memEQs(RExC_start, e + 1 - RExC_start, \"foo\\\\p{Alnum}\") && ! hv_common(GvHVn(PL_incgv), NULL, \"utf8.pm\", sizeof(\"utf8.pm\") - 1, 0, HV_FETCH_ISEXISTS, NULL, 0)) { require_pv(\"utf8.pm\"); } if (! user_defined && \/* We warn on matching an above-Unicode code point * if the match would return true, except don't * warn for \\p{All}, which has exactly one element * = 0 *\/ (_invlist_contains_cp(prop_definition, 0x110000) && (! (_invlist_len(prop_definition) == 1 && *invlist_array(prop_definition) == 0)))) { warn_super = TRUE; } \/* Invert if asking for the complement *\/ if (value == 'P') { _invlist_union_complement_2nd(properties, prop_definition, &properties); } else { _invlist_union(properties, prop_definition, &properties); } } } RExC_parse = e + 1; namedclass = ANYOF_UNIPROP; \/* no official name, but it's named *\/ } break; case 'n': value = '\\n'; break; case 'r': value = '\\r'; break; case 't': value = '\\t'; break; case 'f': value = '\\f'; break; case 'b': value = '\\b'; break; case 'e': value = ESC_NATIVE; break; case 'a': value = '\\a'; break; case 'o': RExC_parse--; \/* function expects to be pointed at the 'o' *\/ { const char* error_msg; bool valid = grok_bslash_o(&RExC_parse, RExC_end, &value, &error_msg, TO_OUTPUT_WARNINGS(RExC_parse), strict, silence_non_portable, UTF); if (! valid) { vFAIL(error_msg); } UPDATE_WARNINGS_LOC(RExC_parse - 1); } non_portable_endpoint++; break; case 'x': RExC_parse--; \/* function expects to be pointed at the 'x' *\/ { const char* error_msg; bool valid = grok_bslash_x(&RExC_parse, RExC_end, &value, &error_msg, TO_OUTPUT_WARNINGS(RExC_parse), strict, silence_non_portable, UTF); if (! valid) { vFAIL(error_msg); } UPDATE_WARNINGS_LOC(RExC_parse - 1); } non_portable_endpoint++; break; case 'c': value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse)); UPDATE_WARNINGS_LOC(RExC_parse); RExC_parse++; non_portable_endpoint++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { \/* Take 1-3 octal digits *\/ I32 flags = PERL_SCAN_SILENT_ILLDIGIT; numlen = (strict) ? 4 : 3; value = grok_oct(--RExC_parse, &numlen, &flags, NULL); RExC_parse += numlen; if (numlen != 3) { if (strict) { RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL(\"Need exactly 3 octal digits\"); } else if ( numlen < 3 \/* like \\08, \\178 *\/ && RExC_parse < RExC_end && isDIGIT(*RExC_parse) && ckWARN(WARN_REGEXP)) { reg_warn_non_literal_string( RExC_parse + 1, form_short_octal_warning(RExC_parse, numlen)); } } non_portable_endpoint++; break; } default: \/* Allow \\_ to not give an error *\/ if (isWORDCHAR(value) && value != '_') { if (strict) { vFAIL2(\"Unrecognized escape \\\\%c in character class\", (int)value); } else { ckWARN2reg(RExC_parse, \"Unrecognized escape \\\\%c in character class passed through\", (int)value); } } break; } \/* End of switch on char following backslash *\/ } \/* end of handling backslash escape sequences *\/ \/* Here, we have the current token in 'value' *\/ if (namedclass > OOB_NAMEDCLASS) { \/* this is a named class \\blah *\/ U8 classnum; \/* a bad range like a-\\d, a-[:digit:]. The '-' is taken as a * literal, as is the character that began the false range, i.e. * the 'a' in the examples *\/ if (range) { const int w = (RExC_parse >= rangebegin) ? RExC_parse - rangebegin : 0; if (strict) { vFAIL2utf8f( \"False [] range \\\"%\" UTF8f \"\\\"\", UTF8fARG(UTF, w, rangebegin)); } else { ckWARN2reg(RExC_parse, \"False [] range \\\"%\" UTF8f \"\\\"\", UTF8fARG(UTF, w, rangebegin)); cp_list = add_cp_to_invlist(cp_list, '-'); cp_foldable_list = add_cp_to_invlist(cp_foldable_list, prevvalue); } range = 0; \/* this was not a true range *\/ element_count += 2; \/* So counts for three values *\/ } classnum = namedclass_to_classnum(namedclass); if (LOC && namedclass < ANYOF_POSIXL_MAX #ifndef HAS_ISASCII && classnum != _CC_ASCII #endif ) { SV* scratch_list = NULL; \/* What the Posix classes (like \\w, [:space:]) match isn't * generally knowable under locale until actual match time. A * special node is used for these which has extra space for a * bitmap, with a bit reserved for each named class that is to * be matched against. (This isn't needed for \\p{} and * pseudo-classes, as they are not affected by locale, and * hence are dealt with separately.) However, if a named class * and its complement are both present, then it matches * everything, and there is no runtime dependency. Odd numbers * are the complements of the next lower number, so xor works. * (Note that something like [\\w\\D] should match everything, * because \\d should be a proper subset of \\w. But rather than * trust that the locale is well behaved, we leave this to * runtime to sort out) *\/ if (POSIXL_TEST(posixl, namedclass ^ 1)) { cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX); POSIXL_ZERO(posixl); has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY; anyof_flags &= ~ANYOF_MATCHES_POSIXL; continue; \/* We could ignore the rest of the class, but best to parse it for any errors *\/ } else { \/* Here, isn't the complement of any already parsed class *\/ POSIXL_SET(posixl, namedclass); has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY; anyof_flags |= ANYOF_MATCHES_POSIXL; \/* The above-Latin1 characters are not subject to locale * rules. Just add them to the unconditionally-matched * list *\/ \/* Get the list of the above-Latin1 code points this * matches *\/ _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1, PL_XPosix_ptrs[classnum], \/* Odd numbers are complements, * like NDIGIT, NASCII, ... *\/ namedclass % 2 != 0, &scratch_list); \/* Checking if 'cp_list' is NULL first saves an extra * clone. Its reference count will be decremented at the * next union, etc, or if this is the only instance, at the * end of the routine *\/ if (! cp_list) { cp_list = scratch_list; } else { _invlist_union(cp_list, scratch_list, &cp_list); SvREFCNT_dec_NN(scratch_list); } continue; \/* Go get next character *\/ } } else { \/* Here, is not \/l, or is a POSIX class for which \/l doesn't * matter (or is a Unicode property, which is skipped here). *\/ if (namedclass >= ANYOF_POSIXL_MAX) { \/* If a special class *\/ if (namedclass != ANYOF_UNIPROP) { \/* UNIPROP = \\p and \\P *\/ \/* Here, should be \\h, \\H, \\v, or \\V. None of \/d, \/i * nor \/l make a difference in what these match, * therefore we just add what they match to cp_list. *\/ if (classnum != _CC_VERTSPACE) { assert( namedclass == ANYOF_HORIZWS || namedclass == ANYOF_NHORIZWS); \/* It turns out that \\h is just a synonym for * XPosixBlank *\/ classnum = _CC_BLANK; } _invlist_union_maybe_complement_2nd( cp_list, PL_XPosix_ptrs[classnum], namedclass % 2 != 0, \/* Complement if odd (NHORIZWS, NVERTWS) *\/ &cp_list); } } else if ( AT_LEAST_UNI_SEMANTICS || classnum == _CC_ASCII || (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT || classnum == _CC_XDIGIT))) { \/* We usually have to worry about \/d affecting what POSIX * classes match, with special code needed because we won't * know until runtime what all matches. But there is no * extra work needed under \/u and \/a; and [:ascii:] is * unaffected by \/d; and :digit: and :xdigit: don't have * runtime differences under \/d. So we can special case * these, and avoid some extra work below, and at runtime. * *\/ _invlist_union_maybe_complement_2nd( simple_posixes, ((AT_LEAST_ASCII_RESTRICTED) ? PL_Posix_ptrs[classnum] : PL_XPosix_ptrs[classnum]), namedclass % 2 != 0, &simple_posixes); } else { \/* Garden variety class. If is NUPPER, NALPHA, ... complement and use nposixes *\/ SV** posixes_ptr = namedclass % 2 == 0 ? &posixes : &nposixes; _invlist_union_maybe_complement_2nd( *posixes_ptr, PL_XPosix_ptrs[classnum], namedclass % 2 != 0, posixes_ptr); } } } \/* end of namedclass \\blah *\/ SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); \/* If 'range' is set, 'value' is the ending of a range--check its * validity. (If value isn't a single code point in the case of a * range, we should have figured that out above in the code that * catches false ranges). Later, we will handle each individual code * point in the range. If 'range' isn't set, this could be the * beginning of a range, so check for that by looking ahead to see if * the next real character to be processed is the range indicator--the * minus sign *\/ if (range) { #ifdef EBCDIC \/* For unicode ranges, we have to test that the Unicode as opposed * to the native values are not decreasing. (Above 255, there is * no difference between native and Unicode) *\/ if (unicode_range && prevvalue < 255 && value < 255) { if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) { goto backwards_range; } } else #endif if (prevvalue > value) \/* b-a *\/ { int w; #ifdef EBCDIC backwards_range: #endif w = RExC_parse - rangebegin; vFAIL2utf8f( \"Invalid [] range \\\"%\" UTF8f \"\\\"\", UTF8fARG(UTF, w, rangebegin)); NOT_REACHED; \/* NOTREACHED *\/ } } else { prevvalue = value; \/* save the beginning of the potential range *\/ if (! stop_at_1 \/* Can't be a range if parsing just one thing *\/ && *RExC_parse == '-') { char* next_char_ptr = RExC_parse + 1; \/* Get the next real char after the '-' *\/ SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr); \/* If the '-' is at the end of the class (just before the ']', * it is a literal minus; otherwise it is a range *\/ if (next_char_ptr < RExC_end && *next_char_ptr != ']') { RExC_parse = next_char_ptr; \/* a bad range like \\w-, [:word:]- ? *\/ if (namedclass > OOB_NAMEDCLASS) { if (strict || ckWARN(WARN_REGEXP)) { const int w = RExC_parse >= rangebegin ? RExC_parse - rangebegin : 0; if (strict) { vFAIL4(\"False [] range \\\"%*.*s\\\"\", w, w, rangebegin); } else { vWARN4(RExC_parse, \"False [] range \\\"%*.*s\\\"\", w, w, rangebegin); } } cp_list = add_cp_to_invlist(cp_list, '-'); element_count++; } else range = 1; \/* yeah, it's a range! *\/ continue; \/* but do it the next time *\/ } } } if (namedclass > OOB_NAMEDCLASS) { continue; } \/* Here, we have a single value this time through the loop, and * is the beginning of the range, if any; or if * not. *\/ \/* non-Latin1 code point implies unicode semantics. *\/ if (value > 255) { REQUIRE_UNI_RULES(flagp, 0); } \/* Ready to process either the single value, or the completed range. * For single-valued non-inverted ranges, we consider the possibility * of multi-char folds. (We made a conscious decision to not do this * for the other cases because it can often lead to non-intuitive * results. For example, you have the peculiar case that: * \"s s\" =~ \/^[^\\xDF]+$\/i => Y * \"ss\" =~ \/^[^\\xDF]+$\/i => N * * See [perl #89750] *\/ if (FOLD && allow_mutiple_chars && value == prevvalue) { if ( value == LATIN_SMALL_LETTER_SHARP_S || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold, value))) { \/* Here is indeed a multi-char fold. Get what it is *\/ U8 foldbuf[UTF8_MAXBYTES_CASE+1]; STRLEN foldlen; UV folded = _to_uni_fold_flags( value, foldbuf, &foldlen, FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED ? FOLD_FLAGS_NOMIX_ASCII : 0) ); \/* Here, should be the first character of the * multi-char fold of , with containing the * whole thing. But, if this fold is not allowed (because of * the flags), will be the same as , and should * be processed like any other character, so skip the special * handling *\/ if (folded != value) { \/* Skip if we are recursed, currently parsing the class * again. Otherwise add this character to the list of * multi-char folds. *\/ if (! RExC_in_multi_char_class) { STRLEN cp_count = utf8_length(foldbuf, foldbuf + foldlen); SV* multi_fold = sv_2mortal(newSVpvs(\"\")); Perl_sv_catpvf(aTHX_ multi_fold, \"\\\\x{%\" UVXf \"}\", value); multi_char_matches = add_multi_match(multi_char_matches, multi_fold, cp_count); } \/* This element should not be processed further in this * class *\/ element_count--; value = save_value; prevvalue = save_prevvalue; continue; } } } if (strict && ckWARN(WARN_REGEXP)) { if (range) { \/* If the range starts above 255, everything is portable and * likely to be so for any forseeable character set, so don't * warn. *\/ if (unicode_range && non_portable_endpoint && prevvalue < 256) { vWARN(RExC_parse, \"Both or neither range ends should be Unicode\"); } else if (prevvalue != value) { \/* Under strict, ranges that stop and\/or end in an ASCII * printable should have each end point be a portable value * for it (preferably like 'A', but we don't warn if it is * a (portable) Unicode name or code point), and the range * must be be all digits or all letters of the same case. * Otherwise, the range is non-portable and unclear as to * what it contains *\/ if ( (isPRINT_A(prevvalue) || isPRINT_A(value)) && ( non_portable_endpoint || ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value)) || (isLOWER_A(prevvalue) && isLOWER_A(value)) || (isUPPER_A(prevvalue) && isUPPER_A(value)) ))) { vWARN(RExC_parse, \"Ranges of ASCII printables should\" \" be some subset of \\\"0-9\\\",\" \" \\\"A-Z\\\", or \\\"a-z\\\"\"); } else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) { SSize_t index_start; SSize_t index_final; \/* But the nature of Unicode and languages mean we * can't do the same checks for above-ASCII ranges, * except in the case of digit ones. These should * contain only digits from the same group of 10. The * ASCII case is handled just above. Hence here, the * range could be a range of digits. First some * unlikely special cases. Grandfather in that a range * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad * if its starting value is one of the 10 digits prior * to it. This is because it is an alternate way of * writing 19D1, and some people may expect it to be in * that group. But it is bad, because it won't give * the expected results. In Unicode 5.2 it was * considered to be in that group (of 11, hence), but * this was fixed in the next version *\/ if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) { goto warn_bad_digit_range; } else if (UNLIKELY( prevvalue >= 0x1D7CE && value <= 0x1D7FF)) { \/* This is the only other case currently in Unicode * where the algorithm below fails. The code * points just above are the end points of a single * range containing only decimal digits. It is 5 * different series of 0-9. All other ranges of * digits currently in Unicode are just a single * series. (And mktables will notify us if a later * Unicode version breaks this.) * * If the range being checked is at most 9 long, * and the digit values represented are in * numerical order, they are from the same series. * *\/ if ( value - prevvalue > 9 || ((( value - 0x1D7CE) % 10) <= (prevvalue - 0x1D7CE) % 10)) { goto warn_bad_digit_range; } } else { \/* For all other ranges of digits in Unicode, the * algorithm is just to check if both end points * are in the same series, which is the same range. * *\/ index_start = _invlist_search( PL_XPosix_ptrs[_CC_DIGIT], prevvalue); \/* Warn if the range starts and ends with a digit, * and they are not in the same group of 10. *\/ if ( index_start >= 0 && ELEMENT_RANGE_MATCHES_INVLIST(index_start) && (index_final = _invlist_search(PL_XPosix_ptrs[_CC_DIGIT], value)) != index_start && index_final >= 0 && ELEMENT_RANGE_MATCHES_INVLIST(index_final)) { warn_bad_digit_range: vWARN(RExC_parse, \"Ranges of digits should be\" \" from the same group of\" \" 10\"); } } } } } if ((! range || prevvalue == value) && non_portable_endpoint) { if (isPRINT_A(value)) { char literal[3]; unsigned d = 0; if (isBACKSLASHED_PUNCT(value)) { literal[d++] = '\\\\'; } literal[d++] = (char) value; literal[d++] = '\\0'; vWARN4(RExC_parse, \"\\\"%.*s\\\" is more clearly written simply as \\\"%s\\\"\", (int) (RExC_parse - rangebegin), rangebegin, literal ); } else if isMNEMONIC_CNTRL(value) { vWARN4(RExC_parse, \"\\\"%.*s\\\" is more clearly written simply as \\\"%s\\\"\", (int) (RExC_parse - rangebegin), rangebegin, cntrl_to_mnemonic((U8) value) ); } } } \/* Deal with this element of the class *\/ #ifndef EBCDIC cp_foldable_list = _add_range_to_invlist(cp_foldable_list, prevvalue, value); #else \/* On non-ASCII platforms, for ranges that span all of 0..255, and ones * that don't require special handling, we can just add the range like * we do for ASCII platforms *\/ if ((UNLIKELY(prevvalue == 0) && value >= 255) || ! (prevvalue < 256 && (unicode_range || (! non_portable_endpoint && ((isLOWER_A(prevvalue) && isLOWER_A(value)) || (isUPPER_A(prevvalue) && isUPPER_A(value))))))) { cp_foldable_list = _add_range_to_invlist(cp_foldable_list, prevvalue, value); } else { \/* Here, requires special handling. This can be because it is a * range whose code points are considered to be Unicode, and so * must be individually translated into native, or because its a * subrange of 'A-Z' or 'a-z' which each aren't contiguous in * EBCDIC, but we have defined them to include only the \"expected\" * upper or lower case ASCII alphabetics. Subranges above 255 are * the same in native and Unicode, so can be added as a range *\/ U8 start = NATIVE_TO_LATIN1(prevvalue); unsigned j; U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255; for (j = start; j <= end; j++) { cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j)); } if (value > 255) { cp_foldable_list = _add_range_to_invlist(cp_foldable_list, 256, value); } } #endif range = 0; \/* this range (if it was one) is done now *\/ } \/* End of loop through all the text within the brackets *\/ if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) { output_posix_warnings(pRExC_state, posix_warnings); } \/* If anything in the class expands to more than one character, we have to * deal with them by building up a substitute parse string, and recursively * calling reg() on it, instead of proceeding *\/ if (multi_char_matches) { SV * substitute_parse = newSVpvn_flags(\"?:\", 2, SVs_TEMP); I32 cp_count; STRLEN len; char *save_end = RExC_end; char *save_parse = RExC_parse; char *save_start = RExC_start; Size_t constructed_prefix_len = 0; \/* This gives the length of the constructed portion of the substitute parse. *\/ bool first_time = TRUE; \/* First multi-char occurrence doesn't get a \"|\" *\/ I32 reg_flags; assert(! invert); \/* Only one level of recursion allowed *\/ assert(RExC_copy_start_in_constructed == RExC_precomp); #if 0 \/* Have decided not to deal with multi-char folds in inverted classes, because too confusing *\/ if (invert) { sv_catpvs(substitute_parse, \"(?:\"); } #endif \/* Look at the longest folds first *\/ for (cp_count = av_tindex_skip_len_mg(multi_char_matches); cp_count > 0; cp_count--) { if (av_exists(multi_char_matches, cp_count)) { AV** this_array_ptr; SV* this_sequence; this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE); while ((this_sequence = av_pop(*this_array_ptr)) != &PL_sv_undef) { if (! first_time) { sv_catpvs(substitute_parse, \"|\"); } first_time = FALSE; sv_catpv(substitute_parse, SvPVX(this_sequence)); } } } \/* If the character class contains anything else besides these * multi-character folds, have to include it in recursive parsing *\/ if (element_count) { sv_catpvs(substitute_parse, \"|[\"); constructed_prefix_len = SvCUR(substitute_parse); sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse); \/* Put in a closing ']' only if not going off the end, as otherwise * we are adding something that really isn't there *\/ if (RExC_parse < RExC_end) { sv_catpvs(substitute_parse, \"]\"); } } sv_catpvs(substitute_parse, \")\"); #if 0 if (invert) { \/* This is a way to get the parse to skip forward a whole named * sequence instead of matching the 2nd character when it fails the * first *\/ sv_catpvs(substitute_parse, \"(*THEN)(*SKIP)(*FAIL)|.)\"); } #endif \/* Set up the data structure so that any errors will be properly * reported. See the comments at the definition of * REPORT_LOCATION_ARGS for details *\/ RExC_copy_start_in_input = (char *) orig_parse; RExC_start = RExC_parse = SvPV(substitute_parse, len); RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len; RExC_end = RExC_parse + len; RExC_in_multi_char_class = 1; ret = reg(pRExC_state, 1, ®_flags, depth+1); *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8); \/* And restore so can parse the rest of the pattern *\/ RExC_parse = save_parse; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start; RExC_end = save_end; RExC_in_multi_char_class = 0; SvREFCNT_dec_NN(multi_char_matches); return ret; } \/* If folding, we calculate all characters that could fold to or from the * ones already on the list *\/ if (cp_foldable_list) { if (FOLD) { UV start, end; \/* End points of code point ranges *\/ SV* fold_intersection = NULL; SV** use_list; \/* Our calculated list will be for Unicode rules. For locale * matching, we have to keep a separate list that is consulted at * runtime only when the locale indicates Unicode rules (and we * don't include potential matches in the ASCII\/Latin1 range, as * any code point could fold to any other, based on the run-time * locale). For non-locale, we just use the general list *\/ if (LOC) { use_list = &only_utf8_locale_list; } else { use_list = &cp_list; } \/* Only the characters in this class that participate in folds need * be checked. Get the intersection of this class and all the * possible characters that are foldable. This can quickly narrow * down a large class *\/ _invlist_intersection(PL_in_some_fold, cp_foldable_list, &fold_intersection); \/* Now look at the foldable characters in this class individually *\/ invlist_iterinit(fold_intersection); while (invlist_iternext(fold_intersection, &start, &end)) { UV j; UV folded; \/* Look at every character in the range *\/ for (j = start; j <= end; j++) { U8 foldbuf[UTF8_MAXBYTES_CASE+1]; STRLEN foldlen; unsigned int k; Size_t folds_count; unsigned int first_fold; const unsigned int * remaining_folds; if (j < 256) { \/* Under \/l, we don't know what code points below 256 * fold to, except we do know the MICRO SIGN folds to * an above-255 character if the locale is UTF-8, so we * add it to the special list (in *use_list) Otherwise * we know now what things can match, though some folds * are valid under \/d only if the target is UTF-8. * Those go in a separate list *\/ if ( IS_IN_SOME_FOLD_L1(j) && ! (LOC && j != MICRO_SIGN)) { \/* ASCII is always matched; non-ASCII is matched * only under Unicode rules (which could happen * under \/l if the locale is a UTF-8 one *\/ if (isASCII(j) || ! DEPENDS_SEMANTICS) { *use_list = add_cp_to_invlist(*use_list, PL_fold_latin1[j]); } else if (j != PL_fold_latin1[j]) { upper_latin1_only_utf8_matches = add_cp_to_invlist( upper_latin1_only_utf8_matches, PL_fold_latin1[j]); } } if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j) && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED)) { add_above_Latin1_folds(pRExC_state, (U8) j, use_list); } continue; } \/* Here is an above Latin1 character. We don't have the * rules hard-coded for it. First, get its fold. This is * the simple fold, as the multi-character folds have been * handled earlier and separated out *\/ folded = _to_uni_fold_flags(j, foldbuf, &foldlen, (ASCII_FOLD_RESTRICTED) ? FOLD_FLAGS_NOMIX_ASCII : 0); \/* Single character fold of above Latin1. Add everything * in its fold closure to the list that this node should * match. *\/ folds_count = _inverse_folds(folded, &first_fold, &remaining_folds); for (k = 0; k <= folds_count; k++) { UV c = (k == 0) \/* First time through use itself *\/ ? folded : (k == 1) \/* 2nd time use, the first fold *\/ ? first_fold \/* Then the remaining ones *\/ : remaining_folds[k-2]; \/* \/aa doesn't allow folds between ASCII and non- *\/ if (( ASCII_FOLD_RESTRICTED && (isASCII(c) != isASCII(j)))) { continue; } \/* Folds under \/l which cross the 255\/256 boundary are * added to a separate list. (These are valid only * when the locale is UTF-8.) *\/ if (c < 256 && LOC) { *use_list = add_cp_to_invlist(*use_list, c); continue; } if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS) { cp_list = add_cp_to_invlist(cp_list, c); } else { \/* Similarly folds involving non-ascii Latin1 * characters under \/d are added to their list *\/ upper_latin1_only_utf8_matches = add_cp_to_invlist( upper_latin1_only_utf8_matches, c); } } } } SvREFCNT_dec_NN(fold_intersection); } \/* Now that we have finished adding all the folds, there is no reason * to keep the foldable list separate *\/ _invlist_union(cp_list, cp_foldable_list, &cp_list); SvREFCNT_dec_NN(cp_foldable_list); } \/* And combine the result (if any) with any inversion lists from posix * classes. The lists are kept separate up to now because we don't want to * fold the classes *\/ if (simple_posixes) { \/* These are the classes known to be unaffected by \/a, \/aa, and \/d *\/ if (cp_list) { _invlist_union(cp_list, simple_posixes, &cp_list); SvREFCNT_dec_NN(simple_posixes); } else { cp_list = simple_posixes; } } if (posixes || nposixes) { if (! DEPENDS_SEMANTICS) { \/* For everything but \/d, we can just add the current 'posixes' and * 'nposixes' to the main list *\/ if (posixes) { if (cp_list) { _invlist_union(cp_list, posixes, &cp_list); SvREFCNT_dec_NN(posixes); } else { cp_list = posixes; } } if (nposixes) { if (cp_list) { _invlist_union(cp_list, nposixes, &cp_list); SvREFCNT_dec_NN(nposixes); } else { cp_list = nposixes; } } } else { \/* Under \/d, things like \\w match upper Latin1 characters only if * the target string is in UTF-8. But things like \\W match all the * upper Latin1 characters if the target string is not in UTF-8. * * Handle the case with something like \\W separately *\/ if (nposixes) { SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL); \/* A complemented posix class matches all upper Latin1 * characters if not in UTF-8. And it matches just certain * ones when in UTF-8. That means those certain ones are * matched regardless, so can just be added to the * unconditional list *\/ if (cp_list) { _invlist_union(cp_list, nposixes, &cp_list); SvREFCNT_dec_NN(nposixes); nposixes = NULL; } else { cp_list = nposixes; } \/* Likewise for 'posixes' *\/ _invlist_union(posixes, cp_list, &cp_list); SvREFCNT_dec(posixes); \/* Likewise for anything else in the range that matched only * under UTF-8 *\/ if (upper_latin1_only_utf8_matches) { _invlist_union(cp_list, upper_latin1_only_utf8_matches, &cp_list); SvREFCNT_dec_NN(upper_latin1_only_utf8_matches); upper_latin1_only_utf8_matches = NULL; } \/* If we don't match all the upper Latin1 characters regardless * of UTF-8ness, we have to set a flag to match the rest when * not in UTF-8 *\/ _invlist_subtract(only_non_utf8_list, cp_list, &only_non_utf8_list); if (_invlist_len(only_non_utf8_list) != 0) { anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER; } SvREFCNT_dec_NN(only_non_utf8_list); } else { \/* Here there were no complemented posix classes. That means * the upper Latin1 characters in 'posixes' match only when the * target string is in UTF-8. So we have to add them to the * list of those types of code points, while adding the * remainder to the unconditional list. * * First calculate what they are *\/ SV* nonascii_but_latin1_properties = NULL; _invlist_intersection(posixes, PL_UpperLatin1, &nonascii_but_latin1_properties); \/* And add them to the final list of such characters. *\/ _invlist_union(upper_latin1_only_utf8_matches, nonascii_but_latin1_properties, &upper_latin1_only_utf8_matches); \/* Remove them from what now becomes the unconditional list *\/ _invlist_subtract(posixes, nonascii_but_latin1_properties, &posixes); \/* And add those unconditional ones to the final list *\/ if (cp_list) { _invlist_union(cp_list, posixes, &cp_list); SvREFCNT_dec_NN(posixes); posixes = NULL; } else { cp_list = posixes; } SvREFCNT_dec(nonascii_but_latin1_properties); \/* Get rid of any characters from the conditional list that we * now know are matched unconditionally, which may make that * list empty *\/ _invlist_subtract(upper_latin1_only_utf8_matches, cp_list, &upper_latin1_only_utf8_matches); if (_invlist_len(upper_latin1_only_utf8_matches) == 0) { SvREFCNT_dec_NN(upper_latin1_only_utf8_matches); upper_latin1_only_utf8_matches = NULL; } } } } \/* And combine the result (if any) with any inversion list from properties. * The lists are kept separate up to now so that we can distinguish the two * in regards to matching above-Unicode. A run-time warning is generated * if a Unicode property is matched against a non-Unicode code point. But, * we allow user-defined properties to match anything, without any warning, * and we also suppress the warning if there is a portion of the character * class that isn't a Unicode property, and which matches above Unicode, \\W * or [\\x{110000}] for example. * (Note that in this case, unlike the Posix one above, there is no * , because having a Unicode property * forces Unicode semantics *\/ if (properties) { if (cp_list) { \/* If it matters to the final outcome, see if a non-property * component of the class matches above Unicode. If so, the * warning gets suppressed. This is true even if just a single * such code point is specified, as, though not strictly correct if * another such code point is matched against, the fact that they * are using above-Unicode code points indicates they should know * the issues involved *\/ if (warn_super) { warn_super = ! (invert ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX)); } _invlist_union(properties, cp_list, &cp_list); SvREFCNT_dec_NN(properties); } else { cp_list = properties; } if (warn_super) { anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER; \/* Because an ANYOF node is the only one that warns, this node * can't be optimized into something else *\/ optimizable = FALSE; } } \/* Here, we have calculated what code points should be in the character * class. * * Now we can see about various optimizations. Fold calculation (which we * did above) needs to take place before inversion. Otherwise \/[^k]\/i * would invert to include K, which under \/i would match k, which it * shouldn't. Therefore we can't invert folded locale now, as it won't be * folded until runtime *\/ \/* If we didn't do folding, it's because some information isn't available * until runtime; set the run-time fold flag for these We know to set the * flag if we have a non-NULL list for UTF-8 locales, or the class matches * at least one 0-255 range code point *\/ if (LOC && FOLD) { \/* Some things on the list might be unconditionally included because of * other components. Remove them, and clean up the list if it goes to * 0 elements *\/ if (only_utf8_locale_list && cp_list) { _invlist_subtract(only_utf8_locale_list, cp_list, &only_utf8_locale_list); if (_invlist_len(only_utf8_locale_list) == 0) { SvREFCNT_dec_NN(only_utf8_locale_list); only_utf8_locale_list = NULL; } } if ( only_utf8_locale_list || (cp_list && ( _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I)))) { has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY; anyof_flags |= ANYOFL_FOLD | ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD; } else if (cp_list) { \/* Look to see if a 0-255 code point is in list *\/ UV start, end; invlist_iterinit(cp_list); if (invlist_iternext(cp_list, &start, &end) && start < 256) { anyof_flags |= ANYOFL_FOLD; has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY; } invlist_iterfinish(cp_list); } } else if ( DEPENDS_SEMANTICS && ( upper_latin1_only_utf8_matches || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))) { RExC_seen_d_op = TRUE; has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY; } \/* Optimize inverted patterns (e.g. [^a-z]) when everything is known at * compile time. *\/ if ( cp_list && invert && ! has_runtime_dependency) { _invlist_invert(cp_list); \/* Clear the invert flag since have just done it here *\/ invert = FALSE; } if (ret_invlist) { *ret_invlist = cp_list; return RExC_emit; } \/* All possible optimizations below still have these characteristics. * (Multi-char folds aren't SIMPLE, but they don't get this far in this * routine) *\/ *flagp |= HASWIDTH|SIMPLE; if (anyof_flags & ANYOF_LOCALE_FLAGS) { RExC_contains_locale = 1; } \/* Some character classes are equivalent to other nodes. Such nodes take * up less room, and some nodes require fewer operations to execute, than * ANYOF nodes. EXACTish nodes may be joinable with adjacent nodes to * improve efficiency. *\/ if (optimizable) { PERL_UINT_FAST8_T i; Size_t partial_cp_count = 0; UV start[MAX_FOLD_FROMS+1] = { 0 }; \/* +1 for the folded-to char *\/ UV end[MAX_FOLD_FROMS+1] = { 0 }; if (cp_list) { \/* Count the code points in enough ranges that we would see all the ones possible in any fold in this version of Unicode *\/ invlist_iterinit(cp_list); for (i = 0; i <= MAX_FOLD_FROMS; i++) { if (! invlist_iternext(cp_list, &start[i], &end[i])) { break; } partial_cp_count += end[i] - start[i] + 1; } invlist_iterfinish(cp_list); } \/* If we know at compile time that this matches every possible code * point, any run-time dependencies don't matter *\/ if (start[0] == 0 && end[0] == UV_MAX) { if (invert) { ret = reganode(pRExC_state, OPFAIL, 0); } else { ret = reg_node(pRExC_state, SANY); MARK_NAUGHTY(1); } goto not_anyof; } \/* Similarly, for \/l posix classes, if both a class and its * complement match, any run-time dependencies don't matter *\/ if (posixl) { for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX; namedclass += 2) { if ( POSIXL_TEST(posixl, namedclass) \/* class *\/ && POSIXL_TEST(posixl, namedclass + 1)) \/* its complement *\/ { if (invert) { ret = reganode(pRExC_state, OPFAIL, 0); } else { ret = reg_node(pRExC_state, SANY); MARK_NAUGHTY(1); } goto not_anyof; } } \/* For well-behaved locales, some classes are subsets of others, * so complementing the subset and including the non-complemented * superset should match everything, like [\\D[:alnum:]], and * [[:^alpha:][:alnum:]], but some implementations of locales are * buggy, and khw thinks its a bad idea to have optimization change * behavior, even if it avoids an OS bug in a given case *\/ #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n) \/* If is a single posix \/l class, can optimize to just that op. * Such a node will not match anything in the Latin1 range, as that * is not determinable until runtime, but will match whatever the * class does outside that range. (Note that some classes won't * match anything outside the range, like [:ascii:]) *\/ if ( isSINGLE_BIT_SET(posixl) && (partial_cp_count == 0 || start[0] > 255)) { U8 classnum; SV * class_above_latin1 = NULL; bool already_inverted; bool are_equivalent; \/* Compute which bit is set, which is the same thing as, e.g., * ANYOF_CNTRL. From * https:\/\/graphics.stanford.edu\/~seander\/bithacks.html#IntegerLogDeBruijn * *\/ static const int MultiplyDeBruijnBitPosition2[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; namedclass = MultiplyDeBruijnBitPosition2[(posixl * 0x077CB531U) >> 27]; classnum = namedclass_to_classnum(namedclass); \/* The named classes are such that the inverted number is one * larger than the non-inverted one *\/ already_inverted = namedclass - classnum_to_namedclass(classnum); \/* Create an inversion list of the official property, inverted * if the constructed node list is inverted, and restricted to * only the above latin1 code points, which are the only ones * known at compile time *\/ _invlist_intersection_maybe_complement_2nd( PL_AboveLatin1, PL_XPosix_ptrs[classnum], already_inverted, &class_above_latin1); are_equivalent = _invlistEQ(class_above_latin1, cp_list, FALSE); SvREFCNT_dec_NN(class_above_latin1); if (are_equivalent) { \/* Resolve the run-time inversion flag with this possibly * inverted class *\/ invert = invert ^ already_inverted; ret = reg_node(pRExC_state, POSIXL + invert * (NPOSIXL - POSIXL)); FLAGS(REGNODE_p(ret)) = classnum; goto not_anyof; } } } \/* khw can't think of any other possible transformation involving * these. *\/ if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) { goto is_anyof; } if (! has_runtime_dependency) { \/* If the list is empty, nothing matches. This happens, for * example, when a Unicode property that doesn't match anything is * the only element in the character class (perluniprops.pod notes * such properties). *\/ if (partial_cp_count == 0) { if (invert) { ret = reg_node(pRExC_state, SANY); } else { ret = reganode(pRExC_state, OPFAIL, 0); } goto not_anyof; } \/* If matches everything but \\n *\/ if ( start[0] == 0 && end[0] == '\\n' - 1 && start[1] == '\\n' + 1 && end[1] == UV_MAX) { assert (! invert); ret = reg_node(pRExC_state, REG_ANY); MARK_NAUGHTY(1); goto not_anyof; } } \/* Next see if can optimize classes that contain just a few code points * into an EXACTish node. The reason to do this is to let the * optimizer join this node with adjacent EXACTish ones. * * An EXACTFish node can be generated even if not under \/i, and vice * versa. But care must be taken. An EXACTFish node has to be such * that it only matches precisely the code points in the class, but we * want to generate the least restrictive one that does that, to * increase the odds of being able to join with an adjacent node. For * example, if the class contains [kK], we have to make it an EXACTFAA * node to prevent the KELVIN SIGN from matching. Whether we are under * \/i or not is irrelevant in this case. Less obvious is the pattern * qr\/[\\x{02BC}]n\/i. U+02BC is MODIFIER LETTER APOSTROPHE. That is * supposed to match the single character U+0149 LATIN SMALL LETTER N * PRECEDED BY APOSTROPHE. And so even though there is no simple fold * that includes \\X{02BC}, there is a multi-char fold that does, and so * the node generated for it must be an EXACTFish one. On the other * hand qr\/:\/i should generate a plain EXACT node since the colon * participates in no fold whatsoever, and having it EXACT tells the * optimizer the target string cannot match unless it has a colon in * it. * * We don't typically generate an EXACTish node if doing so would * require changing the pattern to UTF-8, as that affects \/d and * otherwise is slower. However, under \/i, not changing to UTF-8 can * miss some potential multi-character folds. We calculate the * EXACTish node, and then decide if something would be missed if we * don't upgrade *\/ if ( ! posixl && ! invert \/* Only try if there are no more code points in the class than * in the max possible fold *\/ && partial_cp_count > 0 && partial_cp_count <= MAX_FOLD_FROMS + 1 && (start[0] < 256 || UTF || FOLD)) { if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches) { \/* We can always make a single code point class into an * EXACTish node. *\/ if (LOC) { \/* Here is \/l: Use EXACTL, except \/li indicates EXACTFL, * as that means there is a fold not known until runtime so * shows as only a single code point here. *\/ op = (FOLD) ? EXACTFL : EXACTL; } else if (! FOLD) { \/* Not \/l and not \/i *\/ op = (start[0] < 256) ? EXACT : EXACT_ONLY8; } else if (start[0] < 256) { \/* \/i, not \/l, and the code point is small *\/ \/* Under \/i, it gets a little tricky. A code point that * doesn't participate in a fold should be an EXACT node. * We know this one isn't the result of a simple fold, or * there'd be more than one code point in the list, but it * could be part of a multi- character fold. In that case * we better not create an EXACT node, as we would wrongly * be telling the optimizer that this code point must be in * the target string, and that is wrong. This is because * if the sequence around this code point forms a * multi-char fold, what needs to be in the string could be * the code point that folds to the sequence. * * This handles the case of below-255 code points, as we * have an easy look up for those. The next clause handles * the above-256 one *\/ op = IS_IN_SOME_FOLD_L1(start[0]) ? EXACTFU : EXACT; } else { \/* \/i, larger code point. Since we are under \/i, and have just this code point, we know that it can't fold to something else, so PL_InMultiCharFold applies to it *\/ op = _invlist_contains_cp(PL_InMultiCharFold, start[0]) ? EXACTFU_ONLY8 : EXACT_ONLY8; } value = start[0]; } else if ( ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY) && _invlist_contains_cp(PL_in_some_fold, start[0])) { \/* Here, the only runtime dependency, if any, is from \/d, and * the class matches more than one code point, and the lowest * code point participates in some fold. It might be that the * other code points are \/i equivalent to this one, and hence * they would representable by an EXACTFish node. Above, we * eliminated classes that contain too many code points to be * EXACTFish, with the test for MAX_FOLD_FROMS * * First, special case the ASCII fold pairs, like 'B' and 'b'. * We do this because we have EXACTFAA at our disposal for the * ASCII range *\/ if (partial_cp_count == 2 && isASCII(start[0])) { \/* The only ASCII characters that participate in folds are * alphabetics *\/ assert(isALPHA(start[0])); if ( end[0] == start[0] \/* First range is a single character, so 2nd exists *\/ && isALPHA_FOLD_EQ(start[0], start[1])) { \/* Here, is part of an ASCII fold pair *\/ if ( ASCII_FOLD_RESTRICTED || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0])) { \/* If the second clause just above was true, it * means we can't be under \/i, or else the list * would have included more than this fold pair. * Therefore we have to exclude the possibility of * whatever else it is that folds to these, by * using EXACTFAA *\/ op = EXACTFAA; } else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) { \/* Here, there's no simple fold that start[0] is part * of, but there is a multi-character one. If we * are not under \/i, we want to exclude that * possibility; if under \/i, we want to include it * *\/ op = (FOLD) ? EXACTFU : EXACTFAA; } else { \/* Here, the only possible fold start[0] particpates in * is with start[1]. \/i or not isn't relevant *\/ op = EXACTFU; } value = toFOLD(start[0]); } } else if ( ! upper_latin1_only_utf8_matches || ( _invlist_len(upper_latin1_only_utf8_matches) == 2 && PL_fold_latin1[ invlist_highest(upper_latin1_only_utf8_matches)] == start[0])) { \/* Here, the smallest character is non-ascii or there are * more than 2 code points matched by this node. Also, we * either don't have \/d UTF-8 dependent matches, or if we * do, they look like they could be a single character that * is the fold of the lowest one in the always-match list. * This test quickly excludes most of the false positives * when there are \/d UTF-8 depdendent matches. These are * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN * SMALL LETTER A WITH GRAVE iff the target string is * UTF-8. (We don't have to worry above about exceeding * the array bounds of PL_fold_latin1[] because any code * point in 'upper_latin1_only_utf8_matches' is below 256.) * * EXACTFAA would apply only to pairs (hence exactly 2 code * points) in the ASCII range, so we can't use it here to * artificially restrict the fold domain, so we check if * the class does or does not match some EXACTFish node. * Further, if we aren't under \/i, and and the folded-to * character is part of a multi-character fold, we can't do * this optimization, as the sequence around it could be * that multi-character fold, and we don't here know the * context, so we have to assume it is that multi-char * fold, to prevent potential bugs. * * To do the general case, we first find the fold of the * lowest code point (which may be higher than the lowest * one), then find everything that folds to it. (The data * structure we have only maps from the folded code points, * so we have to do the earlier step.) *\/ Size_t foldlen; U8 foldbuf[UTF8_MAXBYTES_CASE]; UV folded = _to_uni_fold_flags(start[0], foldbuf, &foldlen, 0); unsigned int first_fold; const unsigned int * remaining_folds; Size_t folds_to_this_cp_count = _inverse_folds( folded, &first_fold, &remaining_folds); Size_t folds_count = folds_to_this_cp_count + 1; SV * fold_list = _new_invlist(folds_count); unsigned int i; \/* If there are UTF-8 dependent matches, create a temporary * list of what this node matches, including them. *\/ SV * all_cp_list = NULL; SV ** use_this_list = &cp_list; if (upper_latin1_only_utf8_matches) { all_cp_list = _new_invlist(0); use_this_list = &all_cp_list; _invlist_union(cp_list, upper_latin1_only_utf8_matches, use_this_list); } \/* Having gotten everything that participates in the fold * containing the lowest code point, we turn that into an * inversion list, making sure everything is included. *\/ fold_list = add_cp_to_invlist(fold_list, start[0]); fold_list = add_cp_to_invlist(fold_list, folded); if (folds_to_this_cp_count > 0) { fold_list = add_cp_to_invlist(fold_list, first_fold); for (i = 0; i + 1 < folds_to_this_cp_count; i++) { fold_list = add_cp_to_invlist(fold_list, remaining_folds[i]); } } \/* If the fold list is identical to what's in this ANYOF * node, the node can be represented by an EXACTFish one * instead *\/ if (_invlistEQ(*use_this_list, fold_list, 0 \/* Don't complement *\/ ) ) { \/* But, we have to be careful, as mentioned above. * Just the right sequence of characters could match * this if it is part of a multi-character fold. That * IS what we want if we are under \/i. But it ISN'T * what we want if not under \/i, as it could match when * it shouldn't. So, when we aren't under \/i and this * character participates in a multi-char fold, we * don't optimize into an EXACTFish node. So, for each * case below we have to check if we are folding * and if not, if it is not part of a multi-char fold. * *\/ if (start[0] > 255) { \/* Highish code point *\/ if (FOLD || ! _invlist_contains_cp( PL_InMultiCharFold, folded)) { op = (LOC) ? EXACTFLU8 : (ASCII_FOLD_RESTRICTED) ? EXACTFAA : EXACTFU_ONLY8; value = folded; } } \/* Below, the lowest code point < 256 *\/ else if ( FOLD && folded == 's' && DEPENDS_SEMANTICS) { \/* An EXACTF node containing a single character 's', can be an EXACTFU if it doesn't get joined with an adjacent 's' *\/ op = EXACTFU_S_EDGE; value = folded; } else if ( FOLD || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0])) { if (upper_latin1_only_utf8_matches) { op = EXACTF; \/* We can't use the fold, as that only matches * under UTF-8 *\/ value = start[0]; } else if ( UNLIKELY(start[0] == MICRO_SIGN) && ! UTF) { \/* EXACTFUP is a special node for this character *\/ op = (ASCII_FOLD_RESTRICTED) ? EXACTFAA : EXACTFUP; value = MICRO_SIGN; } else if ( ASCII_FOLD_RESTRICTED && ! isASCII(start[0])) { \/* For ASCII under \/iaa, we can use EXACTFU below *\/ op = EXACTFAA; value = folded; } else { op = EXACTFU; value = folded; } } } SvREFCNT_dec_NN(fold_list); SvREFCNT_dec(all_cp_list); } } if (op != END) { \/* Here, we have calculated what EXACTish node we would use. * But we don't use it if it would require converting the * pattern to UTF-8, unless not using it could cause us to miss * some folds (hence be buggy) *\/ if (! UTF && value > 255) { SV * in_multis = NULL; assert(FOLD); \/* If there is no code point that is part of a multi-char * fold, then there aren't any matches, so we don't do this * optimization. Otherwise, it could match depending on * the context around us, so we do upgrade *\/ _invlist_intersection(PL_InMultiCharFold, cp_list, &in_multis); if (UNLIKELY(_invlist_len(in_multis) != 0)) { REQUIRE_UTF8(flagp); } else { op = END; } } if (op != END) { U8 len = (UTF) ? UVCHR_SKIP(value) : 1; ret = regnode_guts(pRExC_state, op, len, \"exact\"); FILL_NODE(ret, op); RExC_emit += 1 + STR_SZ(len); STR_LEN(REGNODE_p(ret)) = len; if (len == 1) { *STRING(REGNODE_p(ret)) = (U8) value; } else { uvchr_to_utf8((U8 *) STRING(REGNODE_p(ret)), value); } goto not_anyof; } } } if (! has_runtime_dependency) { \/* See if this can be turned into an ANYOFM node. Think about the * bit patterns in two different bytes. In some positions, the * bits in each will be 1; and in other positions both will be 0; * and in some positions the bit will be 1 in one byte, and 0 in * the other. Let 'n' be the number of positions where the bits * differ. We create a mask which has exactly 'n' 0 bits, each in * a position where the two bytes differ. Now take the set of all * bytes that when ANDed with the mask yield the same result. That * set has 2**n elements, and is representable by just two 8 bit * numbers: the result and the mask. Importantly, matching the set * can be vectorized by creating a word full of the result bytes, * and a word full of the mask bytes, yielding a significant speed * up. Here, see if this node matches such a set. As a concrete * example consider [01], and the byte representing '0' which is * 0x30 on ASCII machines. It has the bits 0011 0000. Take the * mask 1111 1110. If we AND 0x31 and 0x30 with that mask we get * 0x30. Any other bytes ANDed yield something else. So [01], * which is a common usage, is optimizable into ANYOFM, and can * benefit from the speed up. We can only do this on UTF-8 * invariant bytes, because they have the same bit patterns under * UTF-8 as not. *\/ PERL_UINT_FAST8_T inverted = 0; #ifdef EBCDIC const PERL_UINT_FAST8_T max_permissible = 0xFF; #else const PERL_UINT_FAST8_T max_permissible = 0x7F; #endif \/* If doesn't fit the criteria for ANYOFM, invert and try again. * If that works we will instead later generate an NANYOFM, and * invert back when through *\/ if (invlist_highest(cp_list) > max_permissible) { _invlist_invert(cp_list); inverted = 1; } if (invlist_highest(cp_list) <= max_permissible) { UV this_start, this_end; UV lowest_cp = UV_MAX; \/* inited to suppress compiler warn *\/ U8 bits_differing = 0; Size_t full_cp_count = 0; bool first_time = TRUE; \/* Go through the bytes and find the bit positions that differ * *\/ invlist_iterinit(cp_list); while (invlist_iternext(cp_list, &this_start, &this_end)) { unsigned int i = this_start; if (first_time) { if (! UVCHR_IS_INVARIANT(i)) { goto done_anyofm; } first_time = FALSE; lowest_cp = this_start; \/* We have set up the code point to compare with. * Don't compare it with itself *\/ i++; } \/* Find the bit positions that differ from the lowest code * point in the node. Keep track of all such positions by * OR'ing *\/ for (; i <= this_end; i++) { if (! UVCHR_IS_INVARIANT(i)) { goto done_anyofm; } bits_differing |= i ^ lowest_cp; } full_cp_count += this_end - this_start + 1; } invlist_iterfinish(cp_list); \/* At the end of the loop, we count how many bits differ from * the bits in lowest code point, call the count 'd'. If the * set we found contains 2**d elements, it is the closure of * all code points that differ only in those bit positions. To * convince yourself of that, first note that the number in the * closure must be a power of 2, which we test for. The only * way we could have that count and it be some differing set, * is if we got some code points that don't differ from the * lowest code point in any position, but do differ from each * other in some other position. That means one code point has * a 1 in that position, and another has a 0. But that would * mean that one of them differs from the lowest code point in * that position, which possibility we've already excluded. *\/ if ( (inverted || full_cp_count > 1) && full_cp_count == 1U << PL_bitcount[bits_differing]) { U8 ANYOFM_mask; op = ANYOFM + inverted;; \/* We need to make the bits that differ be 0's *\/ ANYOFM_mask = ~ bits_differing; \/* This goes into FLAGS *\/ \/* The argument is the lowest code point *\/ ret = reganode(pRExC_state, op, lowest_cp); FLAGS(REGNODE_p(ret)) = ANYOFM_mask; } } done_anyofm: if (inverted) { _invlist_invert(cp_list); } if (op != END) { goto not_anyof; } } if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) { PERL_UINT_FAST8_T type; SV * intersection = NULL; SV* d_invlist = NULL; \/* See if this matches any of the POSIX classes. The POSIXA and * POSIXD ones are about the same speed as ANYOF ops, but take less * room; the ones that have above-Latin1 code point matches are * somewhat faster than ANYOF. *\/ for (type = POSIXA; type >= POSIXD; type--) { int posix_class; if (type == POSIXL) { \/* But not \/l posix classes *\/ continue; } for (posix_class = 0; posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC; posix_class++) { SV** our_code_points = &cp_list; SV** official_code_points; int try_inverted; if (type == POSIXA) { official_code_points = &PL_Posix_ptrs[posix_class]; } else { official_code_points = &PL_XPosix_ptrs[posix_class]; } \/* Skip non-existent classes of this type. e.g. \\v only * has an entry in PL_XPosix_ptrs *\/ if (! *official_code_points) { continue; } \/* Try both the regular class, and its inversion *\/ for (try_inverted = 0; try_inverted < 2; try_inverted++) { bool this_inverted = invert ^ try_inverted; if (type != POSIXD) { \/* This class that isn't \/d can't match if we have * \/d dependencies *\/ if (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY) { continue; } } else \/* is \/d *\/ if (! this_inverted) { \/* \/d classes don't match anything non-ASCII below * 256 unconditionally (which cp_list contains) *\/ _invlist_intersection(cp_list, PL_UpperLatin1, &intersection); if (_invlist_len(intersection) != 0) { continue; } SvREFCNT_dec(d_invlist); d_invlist = invlist_clone(cp_list, NULL); \/* But under UTF-8 it turns into using \/u rules. * Add the things it matches under these conditions * so that we check below that these are identical * to what the tested class should match *\/ if (upper_latin1_only_utf8_matches) { _invlist_union( d_invlist, upper_latin1_only_utf8_matches, &d_invlist); } our_code_points = &d_invlist; } else { \/* POSIXD, inverted. If this doesn't have this flag set, it isn't \/d. *\/ if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)) { continue; } our_code_points = &cp_list; } \/* Here, have weeded out some things. We want to see * if the list of characters this node contains * ('*our_code_points') precisely matches those of the * class we are currently checking against * ('*official_code_points'). *\/ if (_invlistEQ(*our_code_points, *official_code_points, try_inverted)) { \/* Here, they precisely match. Optimize this ANYOF * node into its equivalent POSIX one of the * correct type, possibly inverted *\/ ret = reg_node(pRExC_state, (try_inverted) ? type + NPOSIXA - POSIXA : type); FLAGS(REGNODE_p(ret)) = posix_class; SvREFCNT_dec(d_invlist); SvREFCNT_dec(intersection); goto not_anyof; } } } } SvREFCNT_dec(d_invlist); SvREFCNT_dec(intersection); } \/* If didn't find an optimization and there is no need for a * bitmap, optimize to indicate that *\/ if ( start[0] >= NUM_ANYOF_CODE_POINTS && ! LOC && ! upper_latin1_only_utf8_matches && anyof_flags == 0) { UV highest_cp = invlist_highest(cp_list); \/* If the lowest and highest code point in the class have the same * UTF-8 first byte, then all do, and we can store that byte for * regexec.c to use so that it can more quickly scan the target * string for potential matches for this class. We co-opt the the * flags field for this. Zero means, they don't have the same * first byte. We do accept here very large code points (for * future use), but don't bother with this optimization for them, * as it would cause other complications *\/ if (highest_cp > IV_MAX) { anyof_flags = 0; } else { U8 low_utf8[UTF8_MAXBYTES+1]; U8 high_utf8[UTF8_MAXBYTES+1]; (void) uvchr_to_utf8(low_utf8, start[0]); (void) uvchr_to_utf8(high_utf8, invlist_highest(cp_list)); anyof_flags = (low_utf8[0] == high_utf8[0]) ? low_utf8[0] : 0; } op = ANYOFH; } } \/* End of seeing if can optimize it into a different node *\/ is_anyof: \/* It's going to be an ANYOF node. *\/ if (op != ANYOFH) { op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY) ? ANYOFD : ((posixl) ? ANYOFPOSIXL : ((LOC) ? ANYOFL : ANYOF)); } ret = regnode_guts(pRExC_state, op, regarglen[op], \"anyof\"); FILL_NODE(ret, op); \/* We set the argument later *\/ RExC_emit += 1 + regarglen[op]; ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags; \/* Here, contains all the code points we can determine at * compile time that match under all conditions. Go through it, and * for things that belong in the bitmap, put them there, and delete from * . While we are at it, see if everything above 255 is in the * list, and if so, set a flag to speed up execution *\/ populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list); if (posixl) { ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl); } if (invert) { ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT; } \/* Here, the bitmap has been populated with all the Latin1 code points that * always match. Can now add to the overall list those that match only * when the target string is UTF-8 (). * *\/ if (upper_latin1_only_utf8_matches) { if (cp_list) { _invlist_union(cp_list, upper_latin1_only_utf8_matches, &cp_list); SvREFCNT_dec_NN(upper_latin1_only_utf8_matches); } else { cp_list = upper_latin1_only_utf8_matches; } ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP; } set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list, (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION) ? listsv : NULL, only_utf8_locale_list); return ret; not_anyof: \/* Here, the node is getting optimized into something that's not an ANYOF * one. Finish up. *\/ Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start, RExC_parse - orig_parse);; SvREFCNT_dec(cp_list);; return ret;","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":214030,"input":"deliver_message(uschar *id, BOOL forced, BOOL give_up) { int i, rc; int final_yield = DELIVER_ATTEMPTED_NORMAL; time_t now = time(NULL); address_item *addr_last = NULL; uschar *filter_message = NULL; int process_recipients = RECIP_ACCEPT; open_db dbblock; open_db *dbm_file; extern int acl_where; uschar *info = queue_run_pid == (pid_t)0 ? string_sprintf(\"delivering %s\", id) : string_sprintf(\"delivering %s (queue run pid %d)\", id, queue_run_pid); \/* If the D_process_info bit is on, set_process_info() will output debugging information. If not, we want to show this initial information if D_deliver or D_queue_run is set or in verbose mode. *\/ set_process_info(\"%s\", info); if ( !(debug_selector & D_process_info) && (debug_selector & (D_deliver|D_queue_run|D_v)) ) debug_printf(\"%s\\n\", info); \/* Ensure that we catch any subprocesses that are created. Although Exim sets SIG_DFL as its initial default, some routes through the code end up here with it set to SIG_IGN - cases where a non-synchronous delivery process has been forked, but no re-exec has been done. We use sigaction rather than plain signal() on those OS where SA_NOCLDWAIT exists, because we want to be sure it is turned off. (There was a problem on AIX with this.) *\/ #ifdef SA_NOCLDWAIT { struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(SIGCHLD, &act, NULL); } #else signal(SIGCHLD, SIG_DFL); #endif \/* Make the forcing flag available for routers and transports, set up the global message id field, and initialize the count for returned files and the message size. This use of strcpy() is OK because the length id is checked when it is obtained from a command line (the -M or -q options), and otherwise it is known to be a valid message id. *\/ Ustrcpy(message_id, id); f.deliver_force = forced; return_count = 0; message_size = 0; \/* Initialize some flags *\/ update_spool = FALSE; remove_journal = TRUE; \/* Set a known context for any ACLs we call via expansions *\/ acl_where = ACL_WHERE_DELIVERY; \/* Reset the random number generator, so that if several delivery processes are started from a queue runner that has already used random numbers (for sorting), they don't all get the same sequence. *\/ random_seed = 0; \/* Open and lock the message's data file. Exim locks on this one because the header file may get replaced as it is re-written during the delivery process. Any failures cause messages to be written to the log, except for missing files while queue running - another process probably completed delivery. As part of opening the data file, message_subdir gets set. *\/ if ((deliver_datafile = spool_open_datafile(id)) < 0) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ \/* The value of message_size at this point has been set to the data length, plus one for the blank line that notionally precedes the data. *\/ \/* Now read the contents of the header file, which will set up the headers in store, and also the list of recipients and the tree of non-recipients and assorted flags. It updates message_size. If there is a reading or format error, give up; if the message has been around for sufficiently long, remove it. *\/ { uschar * spoolname = string_sprintf(\"%s-H\", id); if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK) { if (errno == ERRNO_SPOOLFORMAT) { struct stat statbuf; if (Ustat(spool_fname(US\"input\", message_subdir, spoolname, US\"\"), &statbuf) == 0) log_write(0, LOG_MAIN, \"Format error in spool file %s: \" \"size=\" OFF_T_FMT, spoolname, statbuf.st_size); else log_write(0, LOG_MAIN, \"Format error in spool file %s\", spoolname); } else log_write(0, LOG_MAIN, \"Error reading spool file %s: %s\", spoolname, strerror(errno)); \/* If we managed to read the envelope data, received_time contains the time the message was received. Otherwise, we can calculate it from the message id. *\/ if (rc != spool_read_hdrerror) { received_time.tv_sec = received_time.tv_usec = 0; \/*XXX subsec precision?*\/ for (i = 0; i < 6; i++) received_time.tv_sec = received_time.tv_sec * BASE_62 + tab62[id[i] - '0']; } \/* If we've had this malformed message too long, sling it. *\/ if (now - received_time.tv_sec > keep_malformed) { Uunlink(spool_fname(US\"msglog\", message_subdir, id, US\"\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-H\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-J\")); log_write(0, LOG_MAIN, \"Message removed because older than %s\", readconf_printtime(keep_malformed)); } (void)close(deliver_datafile); deliver_datafile = -1; return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* The spool header file has been read. Look to see if there is an existing journal file for this message. If there is, it means that a previous delivery attempt crashed (program or host) before it could update the spool header file. Read the list of delivered addresses from the journal and add them to the nonrecipients tree. Then update the spool file. We can leave the journal in existence, as it will get further successful deliveries added to it in this run, and it will be deleted if this function gets to its end successfully. Otherwise it might be needed again. *\/ { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); FILE * jread; if ( (journal_fd = Uopen(fname, O_RDWR|O_APPEND #ifdef O_CLOEXEC | O_CLOEXEC #endif #ifdef O_NOFOLLOW | O_NOFOLLOW #endif , SPOOL_MODE)) >= 0 && lseek(journal_fd, 0, SEEK_SET) == 0 && (jread = fdopen(journal_fd, \"rb\")) ) { while (Ufgets(big_buffer, big_buffer_size, jread)) { int n = Ustrlen(big_buffer); big_buffer[n-1] = 0; tree_add_nonrecipient(big_buffer); DEBUG(D_deliver) debug_printf(\"Previously delivered address %s taken from \" \"journal file\\n\", big_buffer); } rewind(jread); if ((journal_fd = dup(fileno(jread))) < 0) journal_fd = fileno(jread); else (void) fclose(jread); \/* Try to not leak the FILE resource *\/ \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } else if (errno != ENOENT) { log_write(0, LOG_MAIN|LOG_PANIC, \"attempt to open journal for reading gave: \" \"%s\", strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* A null recipients list indicates some kind of disaster. *\/ if (!recipients_list) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN, \"Spool error: no recipients for %s\", fname); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* Handle a message that is frozen. There are a number of different things that can happen, but in the default situation, unless forced, no delivery is attempted. *\/ if (f.deliver_freeze) { #ifdef SUPPORT_MOVE_FROZEN_MESSAGES \/* Moving to another directory removes the message from Exim's view. Other tools must be used to deal with it. Logging of this action happens in spool_move_message() and its subfunctions. *\/ if ( move_frozen_messages && spool_move_message(id, message_subdir, US\"\", US\"F\") ) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ #endif \/* For all frozen messages (bounces or not), timeout_frozen_after sets the maximum time to keep messages that are frozen. Thaw if we reach it, with a flag causing all recipients to be failed. The time is the age of the message, not the time since freezing. *\/ if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after) { log_write(0, LOG_MAIN, \"cancelled by timeout_frozen_after\"); process_recipients = RECIP_FAIL_TIMEOUT; } \/* For bounce messages (and others with no sender), thaw if the error message ignore timer is exceeded. The message will be discarded if this delivery fails. *\/ else if (!*sender_address && message_age >= ignore_bounce_errors_after) log_write(0, LOG_MAIN, \"Unfrozen by errmsg timer\"); \/* If this is a bounce message, or there's no auto thaw, or we haven't reached the auto thaw time yet, and this delivery is not forced by an admin user, do not attempt delivery of this message. Note that forced is set for continuing messages down the same channel, in order to skip load checking and ignore hold domains, but we don't want unfreezing in that case. *\/ else { if ( ( sender_address[0] == 0 || auto_thaw <= 0 || now <= deliver_frozen_at + auto_thaw ) && ( !forced || !f.deliver_force_thaw || !f.admin_user || continue_hostname ) ) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(L_skip_delivery, LOG_MAIN, \"Message is frozen\"); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* If delivery was forced (by an admin user), assume a manual thaw. Otherwise it's an auto thaw. *\/ if (forced) { f.deliver_manual_thaw = TRUE; log_write(0, LOG_MAIN, \"Unfrozen by forced delivery\"); } else log_write(0, LOG_MAIN, \"Unfrozen by auto-thaw\"); } \/* We get here if any of the rules for unfreezing have triggered. *\/ f.deliver_freeze = FALSE; update_spool = TRUE; } \/* Open the message log file if we are using them. This records details of deliveries, deferments, and failures for the benefit of the mail administrator. The log is not used by exim itself to track the progress of a message; that is done by rewriting the header spool file. *\/ if (message_logs) { uschar * fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); uschar * error; int fd; if ((fd = open_msglog_file(fname, SPOOL_MODE, &error)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't %s message log %s: %s\", error, fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Make a C stream out of it. *\/ if (!(message_log = fdopen(fd, \"a\"))) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't fdopen message log %s: %s\", fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* If asked to give up on a message, log who did it, and set the action for all the addresses. *\/ if (give_up) { struct passwd *pw = getpwuid(real_uid); log_write(0, LOG_MAIN, \"cancelled by %s\", pw ? US pw->pw_name : string_sprintf(\"uid %ld\", (long int)real_uid)); process_recipients = RECIP_FAIL; } \/* Otherwise, if there are too many Received: headers, fail all recipients. *\/ else if (received_count > received_headers_max) process_recipients = RECIP_FAIL_LOOP; \/* Otherwise, if a system-wide, address-independent message filter is specified, run it now, except in the case when we are failing all recipients as a result of timeout_frozen_after. If the system filter yields \"delivered\", then ignore the true recipients of the message. Failure of the filter file is logged, and the delivery attempt fails. *\/ else if (system_filter && process_recipients != RECIP_FAIL_TIMEOUT) { int rc; int filtertype; ugid_block ugid; redirect_block redirect; if (system_filter_uid_set) { ugid.uid = system_filter_uid; ugid.gid = system_filter_gid; ugid.uid_set = ugid.gid_set = TRUE; } else { ugid.uid_set = ugid.gid_set = FALSE; } return_path = sender_address; f.enable_dollar_recipients = TRUE; \/* Permit $recipients in system filter *\/ f.system_filtering = TRUE; \/* Any error in the filter file causes a delivery to be abandoned. *\/ redirect.string = system_filter; redirect.isfile = TRUE; redirect.check_owner = redirect.check_group = FALSE; redirect.owners = NULL; redirect.owngroups = NULL; redirect.pw = NULL; redirect.modemask = 0; DEBUG(D_deliver|D_filter) debug_printf(\"running system filter\\n\"); rc = rda_interpret( &redirect, \/* Where the data is *\/ RDO_DEFER | \/* Turn on all the enabling options *\/ RDO_FAIL | \/* Leave off all the disabling options *\/ RDO_FILTER | RDO_FREEZE | RDO_REALLOG | RDO_REWRITE, NULL, \/* No :include: restriction (not used in filter) *\/ NULL, \/* No sieve vacation directory (not sieve!) *\/ NULL, \/* No sieve enotify mailto owner (not sieve!) *\/ NULL, \/* No sieve user address (not sieve!) *\/ NULL, \/* No sieve subaddress (not sieve!) *\/ &ugid, \/* uid\/gid data *\/ &addr_new, \/* Where to hang generated addresses *\/ &filter_message, \/* Where to put error message *\/ NULL, \/* Don't skip syntax errors *\/ &filtertype, \/* Will always be set to FILTER_EXIM for this call *\/ US\"system filter\"); \/* For error messages *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter returned %d\\n\", rc); if (rc == FF_ERROR || rc == FF_NONEXIST) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN|LOG_PANIC, \"Error in system filter: %s\", string_printing(filter_message)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Reset things. If the filter message is an empty string, which can happen for a filter \"fail\" or \"freeze\" command with no text, reset it to NULL. *\/ f.system_filtering = FALSE; f.enable_dollar_recipients = FALSE; if (filter_message && filter_message[0] == 0) filter_message = NULL; \/* Save the values of the system filter variables so that user filters can use them. *\/ memcpy(filter_sn, filter_n, sizeof(filter_sn)); \/* The filter can request that delivery of the original addresses be deferred. *\/ if (rc == FF_DEFER) { process_recipients = RECIP_DEFER; deliver_msglog(\"Delivery deferred by system filter\\n\"); log_write(0, LOG_MAIN, \"Delivery deferred by system filter\"); } \/* The filter can request that a message be frozen, but this does not take place if the message has been manually thawed. In that case, we must unset \"delivered\", which is forced by the \"freeze\" command to make -bF work properly. *\/ else if (rc == FF_FREEZE && !f.deliver_manual_thaw) { f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); process_recipients = RECIP_DEFER; frozen_info = string_sprintf(\" by the system filter%s%s\", filter_message ? US\": \" : US\"\", filter_message ? filter_message : US\"\"); } \/* The filter can request that a message be failed. The error message may be quite long - it is sent back to the sender in the bounce - but we don't want to fill up the log with repetitions of it. If it starts with << then the text between << and >> is written to the log, with the rest left for the bounce message. *\/ else if (rc == FF_FAIL) { uschar *colon = US\"\"; uschar *logmsg = US\"\"; int loglen = 0; process_recipients = RECIP_FAIL_FILTER; if (filter_message) { uschar *logend; colon = US\": \"; if ( filter_message[0] == '<' && filter_message[1] == '<' && (logend = Ustrstr(filter_message, \">>\")) ) { logmsg = filter_message + 2; loglen = logend - logmsg; filter_message = logend + 2; if (filter_message[0] == 0) filter_message = NULL; } else { logmsg = filter_message; loglen = Ustrlen(filter_message); } } log_write(0, LOG_MAIN, \"cancelled by system filter%s%.*s\", colon, loglen, logmsg); } \/* Delivery can be restricted only to those recipients (if any) that the filter specified. *\/ else if (rc == FF_DELIVERED) { process_recipients = RECIP_IGNORE; if (addr_new) log_write(0, LOG_MAIN, \"original recipients ignored (system filter)\"); else log_write(0, LOG_MAIN, \"=> discarded (system filter)\"); } \/* If any new addresses were created by the filter, fake up a \"parent\" for them. This is necessary for pipes, etc., which are expected to have parents, and it also gives some sensible logging for others. Allow pipes, files, and autoreplies, and run them as the filter uid if set, otherwise as the current uid. *\/ if (addr_new) { int uid = (system_filter_uid_set)? system_filter_uid : geteuid(); int gid = (system_filter_gid_set)? system_filter_gid : getegid(); \/* The text \"system-filter\" is tested in transport_set_up_command() and in set_up_shell_command() in the pipe transport, to enable them to permit $recipients, so don't change it here without also changing it there. *\/ address_item *p = addr_new; address_item *parent = deliver_make_addr(US\"system-filter\", FALSE); parent->domain = string_copylc(qualify_domain_recipient); parent->local_part = US\"system-filter\"; \/* As part of this loop, we arrange for addr_last to end up pointing at the final address. This is used if we go on to add addresses for the original recipients. *\/ while (p) { if (parent->child_count == USHRT_MAX) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"system filter generated more \" \"than %d delivery addresses\", USHRT_MAX); parent->child_count++; p->parent = parent; if (testflag(p, af_pfr)) { uschar *tpname; uschar *type; p->uid = uid; p->gid = gid; setflag(p, af_uid_set); setflag(p, af_gid_set); setflag(p, af_allow_file); setflag(p, af_allow_pipe); setflag(p, af_allow_reply); \/* Find the name of the system filter's appropriate pfr transport *\/ if (p->address[0] == '|') { type = US\"pipe\"; tpname = system_filter_pipe_transport; address_pipe = p->address; } else if (p->address[0] == '>') { type = US\"reply\"; tpname = system_filter_reply_transport; } else { if (p->address[Ustrlen(p->address)-1] == '\/') { type = US\"directory\"; tpname = system_filter_directory_transport; } else { type = US\"file\"; tpname = system_filter_file_transport; } address_file = p->address; } \/* Now find the actual transport, first expanding the name. We have set address_file or address_pipe above. *\/ if (tpname) { uschar *tmp = expand_string(tpname); address_file = address_pipe = NULL; if (!tmp) p->message = string_sprintf(\"failed to expand \\\"%s\\\" as a \" \"system filter transport name\", tpname); tpname = tmp; } else p->message = string_sprintf(\"system_filter_%s_transport is unset\", type); if (tpname) { transport_instance *tp; for (tp = transports; tp; tp = tp->next) if (Ustrcmp(tp->name, tpname) == 0) { p->transport = tp; break; } if (!tp) p->message = string_sprintf(\"failed to find \\\"%s\\\" transport \" \"for system filter delivery\", tpname); } \/* If we couldn't set up a transport, defer the delivery, putting the error on the panic log as well as the main log. *\/ if (!p->transport) { address_item *badp = p; p = p->next; if (!addr_last) addr_new = p; else addr_last->next = p; badp->local_part = badp->address; \/* Needed for log line *\/ post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, EXIM_DTYPE_ROUTER, 0); continue; } } \/* End of pfr handling *\/ \/* Either a non-pfr delivery, or we found a transport *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter added %s\\n\", p->address); addr_last = p; p = p->next; } \/* Loop through all addr_new addresses *\/ } } \/* Scan the recipients list, and for every one that is not in the non- recipients tree, add an addr item to the chain of new addresses. If the pno value is non-negative, we must set the onetime parent from it. This which points to the relevant entry in the recipients list. This processing can be altered by the setting of the process_recipients variable, which is changed if recipients are to be ignored, failed, or deferred. This can happen as a result of system filter activity, or if the -Mg option is used to fail all of them. Duplicate addresses are handled later by a different tree structure; we can't just extend the non-recipients tree, because that will be re-written to the spool if the message is deferred, and in any case there are casing complications for local addresses. *\/ if (process_recipients != RECIP_IGNORE) for (i = 0; i < recipients_count; i++) if (!tree_search(tree_nonrecipients, recipients_list[i].address)) { recipient_item *r = recipients_list + i; address_item *new = deliver_make_addr(r->address, FALSE); new->prop.errors_address = r->errors_to; #ifdef SUPPORT_I18N if ((new->prop.utf8_msg = message_smtputf8)) { new->prop.utf8_downcvt = message_utf8_downconvert == 1; new->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1; DEBUG(D_deliver) debug_printf(\"utf8, downconvert %s\\n\", new->prop.utf8_downcvt ? \"yes\" : new->prop.utf8_downcvt_maybe ? \"ifneeded\" : \"no\"); } #endif if (r->pno >= 0) new->onetime_parent = recipients_list[r->pno].address; \/* If DSN support is enabled, set the dsn flags and the original receipt to be passed on to other DSN enabled MTAs *\/ new->dsn_flags = r->dsn_flags & rf_dsnflags; new->dsn_orcpt = r->orcpt; DEBUG(D_deliver) debug_printf(\"DSN: set orcpt: %s flags: %d\\n\", new->dsn_orcpt ? new->dsn_orcpt : US\"\", new->dsn_flags); switch (process_recipients) { \/* RECIP_DEFER is set when a system filter freezes a message. *\/ case RECIP_DEFER: new->next = addr_defer; addr_defer = new; break; \/* RECIP_FAIL_FILTER is set when a system filter has obeyed a \"fail\" command. *\/ case RECIP_FAIL_FILTER: new->message = filter_message ? filter_message : US\"delivery cancelled\"; setflag(new, af_pass_message); goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older than the value in timeout_frozen_after. Treat non-bounce messages similarly to -Mg; for bounce messages we just want to discard, so don't put the address on the failed list. The timeout has already been logged. *\/ case RECIP_FAIL_TIMEOUT: new->message = US\"delivery cancelled; message timed out\"; goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL is set when -Mg has been used. *\/ case RECIP_FAIL: new->message = US\"delivery cancelled by administrator\"; \/* Fall through *\/ \/* Common code for the failure cases above. If this is not a bounce message, put the address on the failed list so that it is used to create a bounce. Otherwise do nothing - this just discards the address. The incident has already been logged. *\/ RECIP_QUEUE_FAILED: if (sender_address[0]) { new->next = addr_failed; addr_failed = new; } break; \/* RECIP_FAIL_LOOP is set when there are too many Received: headers in the message. Process each address as a routing failure; if this is a bounce message, it will get frozen. *\/ case RECIP_FAIL_LOOP: new->message = US\"Too many \\\"Received\\\" headers - suspected mail loop\"; post_process_one(new, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); break; \/* Value should be RECIP_ACCEPT; take this as the safe default. *\/ default: if (!addr_new) addr_new = new; else addr_last->next = new; addr_last = new; break; } #ifndef DISABLE_EVENT if (process_recipients != RECIP_ACCEPT) { uschar * save_local = deliver_localpart; const uschar * save_domain = deliver_domain; deliver_localpart = expand_string( string_sprintf(\"${local_part:%s}\", new->address)); deliver_domain = expand_string( string_sprintf(\"${domain:%s}\", new->address)); (void) event_raise(event_action, US\"msg:fail:internal\", new->message); deliver_localpart = save_local; deliver_domain = save_domain; } #endif } DEBUG(D_deliver) { address_item *p; debug_printf(\"Delivery address list:\\n\"); for (p = addr_new; p; p = p->next) debug_printf(\" %s %s\\n\", p->address, p->onetime_parent ? p->onetime_parent : US\"\"); } \/* Set up the buffers used for copying over the file when delivering. *\/ deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE); deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE); \/* Until there are no more new addresses, handle each one as follows: . If this is a generated address (indicated by the presence of a parent pointer) then check to see whether it is a pipe, file, or autoreply, and if so, handle it directly here. The router that produced the address will have set the allow flags into the address, and also set the uid\/gid required. Having the routers generate new addresses and then checking them here at the outer level is tidier than making each router do the checking, and means that routers don't need access to the failed address queue. . Break up the address into local part and domain, and make lowercased versions of these strings. We also make unquoted versions of the local part. . Handle the percent hack for those domains for which it is valid. . For child addresses, determine if any of the parents have the same address. If so, generate a different string for previous delivery checking. Without this code, if the address spqr generates spqr via a forward or alias file, delivery of the generated spqr stops further attempts at the top level spqr, which is not what is wanted - it may have generated other addresses. . Check on the retry database to see if routing was previously deferred, but only if in a queue run. Addresses that are to be routed are put on the addr_route chain. Addresses that are to be deferred are put on the addr_defer chain. We do all the checking first, so as not to keep the retry database open any longer than necessary. . Now we run the addresses through the routers. A router may put the address on either the addr_local or the addr_remote chain for local or remote delivery, respectively, or put it on the addr_failed chain if it is undeliveable, or it may generate child addresses and put them on the addr_new chain, or it may defer an address. All the chain anchors are passed as arguments so that the routers can be called for verification purposes as well. . If new addresses have been generated by the routers, da capo. *\/ f.header_rewritten = FALSE; \/* No headers rewritten yet *\/ while (addr_new) \/* Loop until all addresses dealt with *\/ { address_item *addr, *parent; \/* Failure to open the retry database is treated the same as if it does not exist. In both cases, dbm_file is NULL. *\/ if (!(dbm_file = dbfn_open(US\"retry\", O_RDONLY, &dbblock, FALSE))) DEBUG(D_deliver|D_retry|D_route|D_hints_lookup) debug_printf(\"no retry data available\\n\"); \/* Scan the current batch of new addresses, to handle pipes, files and autoreplies, and determine which others are ready for routing. *\/ while (addr_new) { int rc; uschar *p; tree_node *tnode; dbdata_retry *domain_retry_record; dbdata_retry *address_retry_record; addr = addr_new; addr_new = addr->next; DEBUG(D_deliver|D_retry|D_route) { debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"Considering: %s\\n\", addr->address); } \/* Handle generated address that is a pipe or a file or an autoreply. *\/ if (testflag(addr, af_pfr)) { \/* If an autoreply in a filter could not generate a syntactically valid address, give up forthwith. Set af_ignore_error so that we don't try to generate a bounce. *\/ if (testflag(addr, af_bad_reply)) { addr->basic_errno = ERRNO_BADADDRESS2; addr->local_part = addr->address; addr->message = US\"filter autoreply generated syntactically invalid recipient\"; addr->prop.ignore_error = TRUE; (void) post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If two different users specify delivery to the same pipe or file or autoreply, there should be two different deliveries, so build a unique string that incorporates the original address, and use this for duplicate testing and recording delivery, and also for retrying. *\/ addr->unique = string_sprintf(\"%s:%s\", addr->address, addr->parent->unique + (testflag(addr->parent, af_homonym)? 3:0)); addr->address_retry_key = addr->domain_retry_key = string_sprintf(\"T:%s\", addr->unique); \/* If a filter file specifies two deliveries to the same pipe or file, we want to de-duplicate, but this is probably not wanted for two mail commands to the same address, where probably both should be delivered. So, we have to invent a different unique string in that case. Just keep piling '>' characters on the front. *\/ if (addr->address[0] == '>') { while (tree_search(tree_duplicates, addr->unique)) addr->unique = string_sprintf(\">%s\", addr->unique); } else if ((tnode = tree_search(tree_duplicates, addr->unique))) { DEBUG(D_deliver|D_route) debug_printf(\"%s is a duplicate address: discarded\\n\", addr->address); addr->dupof = tnode->data.ptr; addr->next = addr_duplicate; addr_duplicate = addr; continue; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); \/* Check for previous delivery *\/ if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->address); child_done(addr, tod_stamp(tod_log)); continue; } \/* Save for checking future duplicates *\/ tree_add_duplicate(addr->unique, addr); \/* Set local part and domain *\/ addr->local_part = addr->address; addr->domain = addr->parent->domain; \/* Ensure that the delivery is permitted. *\/ if (testflag(addr, af_file)) { if (!testflag(addr, af_allow_file)) { addr->basic_errno = ERRNO_FORBIDFILE; addr->message = US\"delivery to file forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (addr->address[0] == '|') { if (!testflag(addr, af_allow_pipe)) { addr->basic_errno = ERRNO_FORBIDPIPE; addr->message = US\"delivery to pipe forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (!testflag(addr, af_allow_reply)) { addr->basic_errno = ERRNO_FORBIDREPLY; addr->message = US\"autoreply forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If the errno field is already set to BADTRANSPORT, it indicates failure to expand a transport string, or find the associated transport, or an unset transport when one is required. Leave this test till now so that the forbid errors are given in preference. *\/ if (addr->basic_errno == ERRNO_BADTRANSPORT) { (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; } \/* Treat \/dev\/null as a special case and abandon the delivery. This avoids having to specify a uid on the transport just for this case. Arrange for the transport name to be logged as \"**bypassed**\". *\/ if (Ustrcmp(addr->address, \"\/dev\/null\") == 0) { uschar *save = addr->transport->name; addr->transport->name = US\"**bypassed**\"; (void)post_process_one(addr, OK, LOG_MAIN, EXIM_DTYPE_TRANSPORT, '='); addr->transport->name = save; continue; \/* with the next new address *\/ } \/* Pipe, file, or autoreply delivery is to go ahead as a normal local delivery. *\/ DEBUG(D_deliver|D_route) debug_printf(\"queued for %s transport\\n\", addr->transport->name); addr->next = addr_local; addr_local = addr; continue; \/* with the next new address *\/ } \/* Handle normal addresses. First, split up into local part and domain, handling the %-hack if necessary. There is the possibility of a defer from a lookup in percent_hack_domains. *\/ if ((rc = deliver_split_address(addr)) == DEFER) { addr->message = US\"cannot check percent_hack_domains\"; addr->basic_errno = ERRNO_LISTDEFER; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Check to see if the domain is held. If so, proceed only if the delivery was forced by hand. *\/ deliver_domain = addr->domain; \/* set $domain *\/ if ( !forced && hold_domains && (rc = match_isinlist(addr->domain, (const uschar **)&hold_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != FAIL ) { if (rc == DEFER) { addr->message = US\"hold_domains lookup deferred\"; addr->basic_errno = ERRNO_LISTDEFER; } else { addr->message = US\"domain is held\"; addr->basic_errno = ERRNO_HELD; } (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Now we can check for duplicates and previously delivered addresses. In order to do this, we have to generate a \"unique\" value for each address, because there may be identical actual addresses in a line of descendents. The \"unique\" field is initialized to the same value as the \"address\" field, but gets changed here to cope with identically-named descendents. *\/ for (parent = addr->parent; parent; parent = parent->parent) if (strcmpic(addr->address, parent->address) == 0) break; \/* If there's an ancestor with the same name, set the homonym flag. This influences how deliveries are recorded. Then add a prefix on the front of the unique address. We use \\n\\ where n starts at 0 and increases each time. It is unlikely to pass 9, but if it does, it may look odd but will still work. This means that siblings or cousins with the same names are treated as duplicates, which is what we want. *\/ if (parent) { setflag(addr, af_homonym); if (parent->unique[0] != '\\\\') addr->unique = string_sprintf(\"\\\\0\\\\%s\", addr->address); else addr->unique = string_sprintf(\"\\\\%c\\\\%s\", parent->unique[1] + 1, addr->address); } \/* Ensure that the domain in the unique field is lower cased, because domains are always handled caselessly. *\/ p = Ustrrchr(addr->unique, '@'); while (*p != 0) { *p = tolower(*p); p++; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->unique); child_done(addr, tod_stamp(tod_log)); continue; } \/* Get the routing retry status, saving the two retry keys (with and without the local part) for subsequent use. If there is no retry record for the standard address routing retry key, we look for the same key with the sender attached, because this form is used by the smtp transport after a 4xx response to RCPT when address_retry_include_sender is true. *\/ addr->domain_retry_key = string_sprintf(\"R:%s\", addr->domain); addr->address_retry_key = string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain); if (dbm_file) { domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key); if ( domain_retry_record && now - domain_retry_record->time_stamp > retry_data_expire ) domain_retry_record = NULL; \/* Ignore if too old *\/ address_retry_record = dbfn_read(dbm_file, addr->address_retry_key); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire ) address_retry_record = NULL; \/* Ignore if too old *\/ if (!address_retry_record) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); address_retry_record = dbfn_read(dbm_file, altkey); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire) address_retry_record = NULL; \/* Ignore if too old *\/ } } else domain_retry_record = address_retry_record = NULL; DEBUG(D_deliver|D_retry) { if (!domain_retry_record) debug_printf(\"no domain retry record\\n\"); if (!address_retry_record) debug_printf(\"no address retry record\\n\"); } \/* If we are sending a message down an existing SMTP connection, we must assume that the message which created the connection managed to route an address to that connection. We do not want to run the risk of taking a long time over routing here, because if we do, the server at the other end of the connection may time it out. This is especially true for messages with lots of addresses. For this kind of delivery, queue_running is not set, so we would normally route all addresses. We take a pragmatic approach and defer routing any addresses that have any kind of domain retry record. That is, we don't even look at their retry times. It doesn't matter if this doesn't work occasionally. This is all just an optimization, after all. The reason for not doing the same for address retries is that they normally arise from 4xx responses, not DNS timeouts. *\/ if (continue_hostname && domain_retry_record) { addr->message = US\"reusing SMTP connection skips previous routing defer\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* If we are in a queue run, defer routing unless there is no retry data or we've passed the next retry time, or this message is forced. In other words, ignore retry data when not in a queue run. However, if the domain retry time has expired, always allow the routing attempt. If it fails again, the address will be failed. This ensures that each address is routed at least once, even after long-term routing failures. If there is an address retry, check that too; just wait for the next retry time. This helps with the case when the temporary error on the address was really message-specific rather than address specific, since it allows other messages through. We also wait for the next retry time if this is a message sent down an existing SMTP connection (even though that will be forced). Otherwise there will be far too many attempts for an address that gets a 4xx error. In fact, after such an error, we should not get here because, the host should not be remembered as one this message needs. However, there was a bug that used to cause this to happen, so it is best to be on the safe side. Even if we haven't reached the retry time in the hints, there is one more check to do, which is for the ultimate address timeout. We only do this check if there is an address retry record and there is not a domain retry record; this implies that previous attempts to handle the address had the retry_use_local_parts option turned on. We use this as an approximation for the destination being like a local delivery, for example delivery over LMTP to an IMAP message store. In this situation users are liable to bump into their quota and thereby have intermittently successful deliveries, which keep the retry record fresh, which can lead to us perpetually deferring messages. *\/ else if ( ( f.queue_running && !f.deliver_force || continue_hostname ) && ( ( domain_retry_record && now < domain_retry_record->next_try && !domain_retry_record->expired ) || ( address_retry_record && now < address_retry_record->next_try ) ) && ( domain_retry_record || !address_retry_record || !retry_ultimate_address_timeout(addr->address_retry_key, addr->domain, address_retry_record, now) ) ) { addr->message = US\"retry time not reached\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* The domain is OK for routing. Remember if retry data exists so it can be cleaned up after a successful delivery. *\/ else { if (domain_retry_record || address_retry_record) setflag(addr, af_dr_retry_exists); addr->next = addr_route; addr_route = addr; DEBUG(D_deliver|D_route) debug_printf(\"%s: queued for routing\\n\", addr->address); } } \/* The database is closed while routing is actually happening. Requests to update it are put on a chain and all processed together at the end. *\/ if (dbm_file) dbfn_close(dbm_file); \/* If queue_domains is set, we don't even want to try routing addresses in those domains. During queue runs, queue_domains is forced to be unset. Optimize by skipping this pass through the addresses if nothing is set. *\/ if (!f.deliver_force && queue_domains) { address_item *okaddr = NULL; while (addr_route) { address_item *addr = addr_route; addr_route = addr->next; deliver_domain = addr->domain; \/* set $domain *\/ if ((rc = match_isinlist(addr->domain, (const uschar **)&queue_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != OK) if (rc == DEFER) { addr->basic_errno = ERRNO_LISTDEFER; addr->message = US\"queue_domains lookup deferred\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } else { addr->next = okaddr; okaddr = addr; } else { addr->basic_errno = ERRNO_QUEUE_DOMAIN; addr->message = US\"domain is in queue_domains\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } } addr_route = okaddr; } \/* Now route those addresses that are not deferred. *\/ while (addr_route) { int rc; address_item *addr = addr_route; const uschar *old_domain = addr->domain; uschar *old_unique = addr->unique; addr_route = addr->next; addr->next = NULL; \/* Just in case some router parameter refers to it. *\/ if (!(return_path = addr->prop.errors_address)) return_path = sender_address; \/* If a router defers an address, add a retry item. Whether or not to use the local part in the key is a property of the router. *\/ if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new, &addr_succeed, v_none)) == DEFER) retry_add_item(addr, addr->router->retry_use_local_part ? string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain) : string_sprintf(\"R:%s\", addr->domain), 0); \/* Otherwise, if there is an existing retry record in the database, add retry items to delete both forms. We must also allow for the possibility of a routing retry that includes the sender address. Since the domain might have been rewritten (expanded to fully qualified) as a result of routing, ensure that the rewritten form is also deleted. *\/ else if (testflag(addr, af_dr_retry_exists)) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); retry_add_item(addr, altkey, rf_delete); retry_add_item(addr, addr->address_retry_key, rf_delete); retry_add_item(addr, addr->domain_retry_key, rf_delete); if (Ustrcmp(addr->domain, old_domain) != 0) retry_add_item(addr, string_sprintf(\"R:%s\", old_domain), rf_delete); } \/* DISCARD is given for :blackhole: and \"seen finish\". The event has been logged, but we need to ensure the address (and maybe parents) is marked done. *\/ if (rc == DISCARD) { address_done(addr, tod_stamp(tod_log)); continue; \/* route next address *\/ } \/* The address is finished with (failed or deferred). *\/ if (rc != OK) { (void)post_process_one(addr, rc, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* route next address *\/ } \/* The address has been routed. If the router changed the domain, it will also have changed the unique address. We have to test whether this address has already been delivered, because it's the unique address that finally gets recorded. *\/ if ( addr->unique != old_unique && tree_search(tree_nonrecipients, addr->unique) != 0 ) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: \" \"discarded\\n\", addr->address); if (addr_remote == addr) addr_remote = addr->next; else if (addr_local == addr) addr_local = addr->next; } \/* If the router has same_domain_copy_routing set, we are permitted to copy the routing for any other addresses with the same domain. This is an optimisation to save repeated DNS lookups for \"standard\" remote domain routing. The option is settable only on routers that generate host lists. We play it very safe, and do the optimization only if the address is routed to a remote transport, there are no header changes, and the domain was not modified by the router. *\/ if ( addr_remote == addr && addr->router->same_domain_copy_routing && !addr->prop.extra_headers && !addr->prop.remove_headers && old_domain == addr->domain ) { address_item **chain = &addr_route; while (*chain) { address_item *addr2 = *chain; if (Ustrcmp(addr2->domain, addr->domain) != 0) { chain = &(addr2->next); continue; } \/* Found a suitable address; take it off the routing list and add it to the remote delivery list. *\/ *chain = addr2->next; addr2->next = addr_remote; addr_remote = addr2; \/* Copy the routing data *\/ addr2->domain = addr->domain; addr2->router = addr->router; addr2->transport = addr->transport; addr2->host_list = addr->host_list; addr2->fallback_hosts = addr->fallback_hosts; addr2->prop.errors_address = addr->prop.errors_address; copyflag(addr2, addr, af_hide_child); copyflag(addr2, addr, af_local_host_removed); DEBUG(D_deliver|D_route) debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\" \"routing %s\\n\" \"Routing for %s copied from %s\\n\", addr2->address, addr2->address, addr->address); } } } \/* Continue with routing the next address. *\/ } \/* Loop to process any child addresses that the routers created, and any rerouted addresses that got put back on the new chain. *\/ \/* Debugging: show the results of the routing *\/ DEBUG(D_deliver|D_retry|D_route) { address_item *p; debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"After routing:\\n Local deliveries:\\n\"); for (p = addr_local; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Remote deliveries:\\n\"); for (p = addr_remote; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Failed addresses:\\n\"); for (p = addr_failed; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Deferred addresses:\\n\"); for (p = addr_defer; p; p = p->next) debug_printf(\" %s\\n\", p->address); } \/* Free any resources that were cached during routing. *\/ search_tidyup(); route_tidyup(); \/* These two variables are set only during routing, after check_local_user. Ensure they are not set in transports. *\/ local_user_gid = (gid_t)(-1); local_user_uid = (uid_t)(-1); \/* Check for any duplicate addresses. This check is delayed until after routing, because the flexibility of the routing configuration means that identical addresses with different parentage may end up being redirected to different addresses. Checking for duplicates too early (as we previously used to) makes this kind of thing not work. *\/ do_duplicate_check(&addr_local); do_duplicate_check(&addr_remote); \/* When acting as an MUA wrapper, we proceed only if all addresses route to a remote transport. The check that they all end up in one transaction happens in the do_remote_deliveries() function. *\/ if ( mua_wrapper && (addr_local || addr_failed || addr_defer) ) { address_item *addr; uschar *which, *colon, *msg; if (addr_local) { addr = addr_local; which = US\"local\"; } else if (addr_defer) { addr = addr_defer; which = US\"deferred\"; } else { addr = addr_failed; which = US\"failed\"; } while (addr->parent) addr = addr->parent; if (addr->message) { colon = US\": \"; msg = addr->message; } else colon = msg = US\"\"; \/* We don't need to log here for a forced failure as it will already have been logged. Defer will also have been logged, but as a defer, so we do need to do the failure logging. *\/ if (addr != addr_failed) log_write(0, LOG_MAIN, \"** %s routing yielded a %s delivery\", addr->address, which); \/* Always write an error to the caller *\/ fprintf(stderr, \"routing %s yielded a %s delivery%s%s\\n\", addr->address, which, colon, msg); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* If this is a run to continue deliveries to an external channel that is already set up, defer any local deliveries. *\/ if (continue_transport) { if (addr_defer) { address_item *addr = addr_defer; while (addr->next) addr = addr->next; addr->next = addr_local; } else addr_defer = addr_local; addr_local = NULL; } \/* Because address rewriting can happen in the routers, we should not really do ANY deliveries until all addresses have been routed, so that all recipients of the message get the same headers. However, this is in practice not always possible, since sometimes remote addresses give DNS timeouts for days on end. The pragmatic approach is to deliver what we can now, saving any rewritten headers so that at least the next lot of recipients benefit from the rewriting that has already been done. If any headers have been rewritten during routing, update the spool file to remember them for all subsequent deliveries. This can be delayed till later if there is only address to be delivered - if it succeeds the spool write need not happen. *\/ if ( f.header_rewritten && ( addr_local && (addr_local->next || addr_remote) || addr_remote && addr_remote->next ) ) { \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); f.header_rewritten = FALSE; } \/* If there are any deliveries to be and we do not already have the journal file, create it. This is used to record successful deliveries as soon as possible after each delivery is known to be complete. A file opened with O_APPEND is used so that several processes can run simultaneously. The journal is just insurance against crashes. When the spool file is ultimately updated at the end of processing, the journal is deleted. If a journal is found to exist at the start of delivery, the addresses listed therein are added to the non-recipients. *\/ if (addr_local || addr_remote) { if (journal_fd < 0) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if ((journal_fd = Uopen(fname, #ifdef O_CLOEXEC O_CLOEXEC | #endif O_WRONLY|O_APPEND|O_CREAT|O_EXCL, SPOOL_MODE)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't open journal file %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } \/* Set the close-on-exec flag, make the file owned by Exim, and ensure that the mode is correct - the group setting doesn't always seem to get set automatically. *\/ if( fchown(journal_fd, exim_uid, exim_gid) || fchmod(journal_fd, SPOOL_MODE) #ifndef O_CLOEXEC || fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC) #endif ) { int ret = Uunlink(fname); log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't set perms on journal file %s: %s\", fname, strerror(errno)); if(ret && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } } } else if (journal_fd >= 0) { close(journal_fd); journal_fd = -1; } \/* Now we can get down to the business of actually doing deliveries. Local deliveries are done first, then remote ones. If ever the problems of how to handle fallback transports are figured out, this section can be put into a loop for handling fallbacks, though the uid switching will have to be revised. *\/ \/* Precompile a regex that is used to recognize a parameter in response to an LHLO command, if is isn't already compiled. This may be used on both local and remote LMTP deliveries. *\/ if (!regex_IGNOREQUOTA) regex_IGNOREQUOTA = regex_must_compile(US\"\\\\n250[\\\\s\\\\-]IGNOREQUOTA(\\\\s|\\\\n|$)\", FALSE, TRUE); \/* Handle local deliveries *\/ if (addr_local) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\\n\"); do_local_deliveries(); f.disable_logging = FALSE; } \/* If queue_run_local is set, we do not want to attempt any remote deliveries, so just queue them all. *\/ if (f.queue_run_local) while (addr_remote) { address_item *addr = addr_remote; addr_remote = addr->next; addr->next = NULL; addr->basic_errno = ERRNO_LOCAL_ONLY; addr->message = US\"remote deliveries suppressed\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_TRANSPORT, 0); } \/* Handle remote deliveries *\/ if (addr_remote) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\\n\"); \/* Precompile some regex that are used to recognize parameters in response to an EHLO command, if they aren't already compiled. *\/ deliver_init(); \/* Now sort the addresses if required, and do the deliveries. The yield of do_remote_deliveries is FALSE when mua_wrapper is set and all addresses cannot be delivered in one transaction. *\/ if (remote_sort_domains) sort_remote_deliveries(); if (!do_remote_deliveries(FALSE)) { log_write(0, LOG_MAIN, \"** mua_wrapper is set but recipients cannot all \" \"be delivered in one transaction\"); fprintf(stderr, \"delivery to smarthost failed (configuration problem)\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* See if any of the addresses that failed got put on the queue for delivery to their fallback hosts. We do it this way because often the same fallback host is used for many domains, so all can be sent in a single transaction (if appropriately configured). *\/ if (addr_fallback && !mua_wrapper) { DEBUG(D_deliver) debug_printf(\"Delivering to fallback hosts\\n\"); addr_remote = addr_fallback; addr_fallback = NULL; if (remote_sort_domains) sort_remote_deliveries(); do_remote_deliveries(TRUE); } f.disable_logging = FALSE; } \/* All deliveries are now complete. Ignore SIGTERM during this tidying up phase, to minimize cases of half-done things. *\/ DEBUG(D_deliver) debug_printf(\">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\\n\"); cancel_cutthrough_connection(TRUE, US\"deliveries are done\"); \/* Root privilege is no longer needed *\/ exim_setugid(exim_uid, exim_gid, FALSE, US\"post-delivery tidying\"); set_process_info(\"tidying up after delivering %s\", message_id); signal(SIGTERM, SIG_IGN); \/* When we are acting as an MUA wrapper, the smtp transport will either have succeeded for all addresses, or failed them all in normal cases. However, there are some setup situations (e.g. when a named port does not exist) that cause an immediate exit with deferral of all addresses. Convert those into failures. We do not ever want to retry, nor do we want to send a bounce message. *\/ if (mua_wrapper) { if (addr_defer) { address_item *addr, *nextaddr; for (addr = addr_defer; addr; addr = nextaddr) { log_write(0, LOG_MAIN, \"** %s mua_wrapper forced failure for deferred \" \"delivery\", addr->address); nextaddr = addr->next; addr->next = addr_failed; addr_failed = addr; } addr_defer = NULL; } \/* Now all should either have succeeded or failed. *\/ if (!addr_failed) final_yield = DELIVER_MUA_SUCCEEDED; else { host_item * host; uschar *s = addr_failed->user_message; if (!s) s = addr_failed->message; fprintf(stderr, \"Delivery failed: \"); if (addr_failed->basic_errno > 0) { fprintf(stderr, \"%s\", strerror(addr_failed->basic_errno)); if (s) fprintf(stderr, \": \"); } if ((host = addr_failed->host_used)) fprintf(stderr, \"H=%s [%s]: \", host->name, host->address); if (s) fprintf(stderr, \"%s\", CS s); else if (addr_failed->basic_errno <= 0) fprintf(stderr, \"unknown error\"); fprintf(stderr, \"\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = NULL; } } \/* In a normal configuration, we now update the retry database. This is done in one fell swoop at the end in order not to keep opening and closing (and locking) the database. The code for handling retries is hived off into a separate module for convenience. We pass it the addresses of the various chains, because deferred addresses can get moved onto the failed chain if the retry cutoff time has expired for all alternative destinations. Bypass the updating of the database if the -N flag is set, which is a debugging thing that prevents actual delivery. *\/ else if (!f.dont_deliver) retry_update(&addr_defer, &addr_failed, &addr_succeed); \/* Send DSN for successful messages if requested *\/ addr_senddsn = NULL; for (addr_dsntmp = addr_succeed; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { \/* af_ignore_error not honored here. it's not an error *\/ DEBUG(D_deliver) debug_printf(\"DSN: processing router : %s\\n\" \"DSN: processing successful delivery address: %s\\n\" \"DSN: Sender_address: %s\\n\" \"DSN: orcpt: %s flags: %d\\n\" \"DSN: envid: %s ret: %d\\n\" \"DSN: Final recipient: %s\\n\" \"DSN: Remote SMTP server supports DSN: %d\\n\", addr_dsntmp->router ? addr_dsntmp->router->name : US\"(unknown)\", addr_dsntmp->address, sender_address, addr_dsntmp->dsn_orcpt ? addr_dsntmp->dsn_orcpt : US\"NULL\", addr_dsntmp->dsn_flags, dsn_envid ? dsn_envid : US\"NULL\", dsn_ret, addr_dsntmp->address, addr_dsntmp->dsn_aware ); \/* send report if next hop not DSN aware or a router flagged \"last DSN hop\" and a report was requested *\/ if ( ( addr_dsntmp->dsn_aware != dsn_support_yes || addr_dsntmp->dsn_flags & rf_dsnlasthop ) && addr_dsntmp->dsn_flags & rf_dsnflags && addr_dsntmp->dsn_flags & rf_notify_success ) { \/* copy and relink address_item and send report with all of them at once later *\/ address_item * addr_next = addr_senddsn; addr_senddsn = store_get(sizeof(address_item)); *addr_senddsn = *addr_dsntmp; addr_senddsn->next = addr_next; } else DEBUG(D_deliver) debug_printf(\"DSN: not sending DSN success message\\n\"); } if (addr_senddsn) { pid_t pid; int fd; \/* create exim process to send message *\/ pid = child_open_exim(&fd); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim returns: %d\\n\", pid); if (pid < 0) \/* Creation of child failed *\/ { log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim failed\\n\"); } else \/* Creation of child succeeded *\/ { FILE *f = fdopen(fd, \"wb\"); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ uschar * bound; transport_ctx tctx = {{0}}; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", sender_address); \/* build unique id for MIME boundary *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); DEBUG(D_deliver) debug_printf(\"DSN: MIME boundary: %s\\n\", bound); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-generated\\n\" \"From: Mail Delivery System \\n\" \"To: %s\\n\" \"Subject: Delivery Status Notification\\n\" \"Content-Type: multipart\/report; report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\\n\" \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\" \"This message was created automatically by mail delivery software.\\n\" \" ----- The following addresses had successful delivery notifications -----\\n\", qualify_domain_sender, sender_address, bound, bound); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) fprintf(f, \"<%s> (relayed %s)\\n\\n\", addr_dsntmp->address, (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? \"via non DSN router\" : addr_dsntmp->dsn_aware == dsn_support_no ? \"to non-DSN-aware mailer\" : \"via non \\\"Remote SMTP\\\" router\" ); fprintf(f, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { if (addr_dsntmp->dsn_orcpt) fprintf(f,\"Original-Recipient: %s\\n\", addr_dsntmp->dsn_orcpt); fprintf(f, \"Action: delivered\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 2.0.0\\n\", addr_dsntmp->address); if (addr_dsntmp->host_used && addr_dsntmp->host_used->name) fprintf(f, \"Remote-MTA: dns; %s\\nDiagnostic-Code: smtp; 250 Ok\\n\\n\", addr_dsntmp->host_used->name); else fprintf(f, \"Diagnostic-Code: X-Exim; relayed via non %s router\\n\\n\", (addr_dsntmp->dsn_flags & rf_dsnlasthop) == 1 ? \"DSN\" : \"SMTP\"); } fprintf(f, \"--%s\\nContent-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); fclose(f); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ } } \/* If any addresses failed, we must send a message to somebody, unless af_ignore_error is set, in which case no action is taken. It is possible for several messages to get sent if there are addresses with different requirements. *\/ while (addr_failed) { pid_t pid; int fd; uschar *logtod = tod_stamp(tod_log); address_item *addr; address_item *handled_addr = NULL; address_item **paddr; address_item *msgchain = NULL; address_item **pmsgchain = &msgchain; \/* There are weird cases when logging is disabled in the transport. However, there may not be a transport (address failed by a router). *\/ f.disable_logging = FALSE; if (addr_failed->transport) f.disable_logging = addr_failed->transport->disable_logging; DEBUG(D_deliver) debug_printf(\"processing failed address %s\\n\", addr_failed->address); \/* There are only two ways an address in a bounce message can get here: (1) When delivery was initially deferred, but has now timed out (in the call to retry_update() above). We can detect this by testing for af_retry_timedout. If the address does not have its own errors address, we arrange to ignore the error. (2) If delivery failures for bounce messages are being ignored. We can detect this by testing for af_ignore_error. This will also be set if a bounce message has been autothawed and the ignore_bounce_errors_after time has passed. It might also be set if a router was explicitly configured to ignore errors (errors_to = \"\"). If neither of these cases obtains, something has gone wrong. Log the incident, but then ignore the error. *\/ if (sender_address[0] == 0 && !addr_failed->prop.errors_address) { if ( !testflag(addr_failed, af_retry_timedout) && !addr_failed->prop.ignore_error) log_write(0, LOG_MAIN|LOG_PANIC, \"internal error: bounce message \" \"failure is neither frozen nor ignored (it's been ignored)\"); addr_failed->prop.ignore_error = TRUE; } \/* If the first address on the list has af_ignore_error set, just remove it from the list, throw away any saved message file, log it, and mark the recipient done. *\/ if ( addr_failed->prop.ignore_error || ( addr_failed->dsn_flags & rf_dsnflags && (addr_failed->dsn_flags & rf_notify_failure) != rf_notify_failure ) ) { addr = addr_failed; addr_failed = addr->next; if (addr->return_filename) Uunlink(addr->return_filename); log_write(0, LOG_MAIN, \"%s%s%s%s: error ignored\", addr->address, !addr->parent ? US\"\" : US\" <\", !addr->parent ? US\"\" : addr->parent->address, !addr->parent ? US\"\" : US\">\"); address_done(addr, logtod); child_done(addr, logtod); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Otherwise, handle the sending of a message. Find the error address for the first address, then send a message that includes all failed addresses that have the same error address. Note the bounce_recipient is a global so that it can be accessed by $bounce_recipient while creating a customized error message. *\/ else { if (!(bounce_recipient = addr_failed->prop.errors_address)) bounce_recipient = sender_address; \/* Make a subprocess to send a message *\/ if ((pid = child_open_exim(&fd)) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); \/* Creation of child succeeded *\/ else { int ch, rc; int filecount = 0; int rcount = 0; uschar *bcc, *emf_text; FILE * fp = fdopen(fd, \"wb\"); FILE * emf = NULL; BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0; int max = (bounce_return_size_limit\/DELIVER_IN_BUFFER_SIZE + 1) * DELIVER_IN_BUFFER_SIZE; uschar * bound; uschar *dsnlimitmsg; uschar *dsnnotifyhdr; int topt; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", bounce_recipient); \/* Scan the addresses for all that have the same errors address, removing them from the addr_failed chain, and putting them on msgchain. *\/ paddr = &addr_failed; for (addr = addr_failed; addr; addr = *paddr) if (Ustrcmp(bounce_recipient, addr->prop.errors_address ? addr->prop.errors_address : sender_address) == 0) { \/* The same - dechain *\/ *paddr = addr->next; *pmsgchain = addr; addr->next = NULL; pmsgchain = &(addr->next); } else paddr = &addr->next; \/* Not the same; skip *\/ \/* Include X-Failed-Recipients: for automatic interpretation, but do not let any one header line get too long. We do this by starting a new header every 50 recipients. Omit any addresses for which the \"hide_child\" flag is set. *\/ for (addr = msgchain; addr; addr = addr->next) { if (testflag(addr, af_hide_child)) continue; if (rcount >= 50) { fprintf(fp, \"\\n\"); rcount = 0; } fprintf(fp, \"%s%s\", rcount++ == 0 ? \"X-Failed-Recipients: \" : \",\\n \", testflag(addr, af_pfr) && addr->parent ? string_printing(addr->parent->address) : string_printing(addr->address)); } if (rcount > 0) fprintf(fp, \"\\n\"); \/* Output the standard headers *\/ if (errors_reply_to) fprintf(fp, \"Reply-To: %s\\n\", errors_reply_to); fprintf(fp, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(fp); fprintf(fp, \"To: %s\\n\", bounce_recipient); \/* generate boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(fp, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); \/* Open a template file if one is provided. Log failure to open, but carry on - default texts will be used. *\/ if (bounce_message_file) if (!(emf = Ufopen(bounce_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for error \" \"message texts: %s\", bounce_message_file, strerror(errno)); \/* Quietly copy to configured additional addresses if required. *\/ if ((bcc = moan_check_errorcopy(bounce_recipient))) fprintf(fp, \"Bcc: %s\\n\", bcc); \/* The texts for the message can be read from a template file; if there isn't one, or if it is too short, built-in texts are used. The first emf text is a Subject: and any other headers. *\/ if ((emf_text = next_emf(emf, US\"header\"))) fprintf(fp, \"%s\\n\", emf_text); else fprintf(fp, \"Subject: Mail delivery failed%s\\n\\n\", to_sender? \": returning message to sender\" : \"\"); \/* output human readable part as text\/plain section *\/ fprintf(fp, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((emf_text = next_emf(emf, US\"intro\"))) fprintf(fp, \"%s\", CS emf_text); else { fprintf(fp, \/* This message has been reworded several times. It seems to be confusing to somebody, however it is worded. I have retreated to the original, simple wording. *\/ \"This message was created automatically by mail delivery software.\\n\"); if (bounce_message_text) fprintf(fp, \"%s\", CS bounce_message_text); if (to_sender) fprintf(fp, \"\\nA message that you sent could not be delivered to one or more of its\\n\" \"recipients. This is a permanent error. The following address(es) failed:\\n\"); else fprintf(fp, \"\\nA message sent by\\n\\n <%s>\\n\\n\" \"could not be delivered to one or more of its recipients. The following\\n\" \"address(es) failed:\\n\", sender_address); } fputc('\\n', fp); \/* Process the addresses, leaving them on the msgchain if they have a file name for a return message. (There has already been a check in post_process_one() for the existence of data in the message file.) A TRUE return from print_address_information() means that the address is not hidden. *\/ paddr = &msgchain; for (addr = msgchain; addr; addr = *paddr) { if (print_address_information(addr, fp, US\" \", US\"\\n \", US\"\")) print_address_error(addr, fp, US\"\"); \/* End the final line for the address *\/ fputc('\\n', fp); \/* Leave on msgchain if there's a return file. *\/ if (addr->return_file >= 0) { paddr = &(addr->next); filecount++; } \/* Else save so that we can tick off the recipient when the message is sent. *\/ else { *paddr = addr->next; addr->next = handled_addr; handled_addr = addr; } } fputc('\\n', fp); \/* Get the next text, whether we need it or not, so as to be positioned for the one after. *\/ emf_text = next_emf(emf, US\"generated text\"); \/* If there were any file messages passed by the local transports, include them in the message. Then put the address on the handled chain. In the case of a batch of addresses that were all sent to the same transport, the return_file field in all of them will contain the same fd, and the return_filename field in the *last* one will be set (to the name of the file). *\/ if (msgchain) { address_item *nextaddr; if (emf_text) fprintf(fp, \"%s\", CS emf_text); else fprintf(fp, \"The following text was generated during the delivery \" \"attempt%s:\\n\", (filecount > 1)? \"s\" : \"\"); for (addr = msgchain; addr; addr = nextaddr) { FILE *fm; address_item *topaddr = addr; \/* List all the addresses that relate to this file *\/ fputc('\\n', fp); while(addr) \/* Insurance *\/ { print_address_information(addr, fp, US\"------ \", US\"\\n \", US\" ------\\n\"); if (addr->return_filename) break; addr = addr->next; } fputc('\\n', fp); \/* Now copy the file *\/ if (!(fm = Ufopen(addr->return_filename, \"rb\"))) fprintf(fp, \" +++ Exim error... failed to open text file: %s\\n\", strerror(errno)); else { while ((ch = fgetc(fm)) != EOF) fputc(ch, fp); (void)fclose(fm); } Uunlink(addr->return_filename); \/* Can now add to handled chain, first fishing off the next address on the msgchain. *\/ nextaddr = addr->next; addr->next = handled_addr; handled_addr = topaddr; } fputc('\\n', fp); } \/* output machine readable part *\/ #ifdef SUPPORT_I18N if (message_smtputf8) fprintf(fp, \"--%s\\n\" \"Content-type: message\/global-delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); else #endif fprintf(fp, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(fp, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(fp, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', fp); for (addr = handled_addr; addr; addr = addr->next) { host_item * hu; fprintf(fp, \"Action: failed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 5.0.0\\n\", addr->address); if ((hu = addr->host_used) && hu->name) { fprintf(fp, \"Remote-MTA: dns; %s\\n\", hu->name); #ifdef EXPERIMENTAL_DSN_INFO { const uschar * s; if (hu->address) { uschar * p = hu->port == 25 ? US\"\" : string_sprintf(\":%d\", hu->port); fprintf(fp, \"Remote-MTA: X-ip; [%s]%s\\n\", hu->address, p); } if ((s = addr->smtp_greeting) && *s) fprintf(fp, \"X-Remote-MTA-smtp-greeting: X-str; %s\\n\", s); if ((s = addr->helo_response) && *s) fprintf(fp, \"X-Remote-MTA-helo-response: X-str; %s\\n\", s); if ((s = addr->message) && *s) fprintf(fp, \"X-Exim-Diagnostic: X-str; %s\\n\", s); } #endif print_dsn_diagnostic_code(addr, fp); } fputc('\\n', fp); } \/* Now copy the message, trying to give an intelligible comment if it is too long for it all to be copied. The limit isn't strictly applied because of the buffering. There is, however, an option to suppress copying altogether. *\/ emf_text = next_emf(emf, US\"copy\"); \/* add message body we ignore the intro text from template and add the text for bounce_return_size_limit at the end. bounce_return_message is ignored in case RET= is defined we honor these values otherwise bounce_return_body is honored. bounce_return_size_limit is always honored. *\/ fprintf(fp, \"--%s\\n\", bound); dsnlimitmsg = US\"X-Exim-DSN-Information: Due to administrative limits only headers are returned\"; dsnnotifyhdr = NULL; topt = topt_add_return_path; \/* RET=HDRS? top priority *\/ if (dsn_ret == dsn_ret_hdrs) topt |= topt_no_body; else { struct stat statbuf; \/* no full body return at all? *\/ if (!bounce_return_body) { topt |= topt_no_body; \/* add header if we overrule RET=FULL *\/ if (dsn_ret == dsn_ret_full) dsnnotifyhdr = dsnlimitmsg; } \/* line length limited... return headers only if oversize *\/ \/* size limited ... return headers only if limit reached *\/ else if ( max_received_linelength > bounce_return_linesize_limit || ( bounce_return_size_limit > 0 && fstat(deliver_datafile, &statbuf) == 0 && statbuf.st_size > max ) ) { topt |= topt_no_body; dsnnotifyhdr = dsnlimitmsg; } } #ifdef SUPPORT_I18N if (message_smtputf8) fputs(topt & topt_no_body ? \"Content-type: message\/global-headers\\n\\n\" : \"Content-type: message\/global\\n\\n\", fp); else #endif fputs(topt & topt_no_body ? \"Content-type: text\/rfc822-headers\\n\\n\" : \"Content-type: message\/rfc822\\n\\n\", fp); fflush(fp); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ { \/* Dummy transport for headers add *\/ transport_ctx tctx = {{0}}; transport_instance tb = {0}; tctx.u.fd = fileno(fp); tctx.tblock = &tb; tctx.options = topt; tb.add_headers = dsnnotifyhdr; transport_write_message(&tctx, 0); } fflush(fp); \/* we never add the final text. close the file *\/ if (emf) (void)fclose(emf); fprintf(fp, \"\\n--%s--\\n\", bound); \/* Close the file, which should send an EOF to the child process that is receiving the message. Wait for it to finish. *\/ (void)fclose(fp); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ \/* In the test harness, let the child do it's thing first. *\/ if (f.running_in_test_harness) millisleep(500); \/* If the process failed, there was some disaster in setting up the error message. Unless the message is very old, ensure that addr_defer is non-null, which will have the effect of leaving the message on the spool. The failed addresses will get tried again next time. However, we don't really want this to happen too often, so freeze the message unless there are some genuine deferred addresses to try. To do this we have to call spool_write_header() here, because with no genuine deferred addresses the normal code below doesn't get run. *\/ if (rc != 0) { uschar *s = US\"\"; if (now - received_time.tv_sec < retry_maximum_timeout && !addr_defer) { addr_defer = (address_item *)(+1); f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); s = US\" (frozen)\"; } deliver_msglog(\"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); log_write(0, LOG_MAIN, \"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); } \/* The message succeeded. Ensure that the recipients that failed are now marked finished with on the spool and their parents updated. *\/ else { for (addr = handled_addr; addr; addr = addr->next) { address_done(addr, logtod); child_done(addr, logtod); } \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } } } } f.disable_logging = FALSE; \/* In case left set *\/ \/* Come here from the mua_wrapper case if routing goes wrong *\/ DELIVERY_TIDYUP: \/* If there are now no deferred addresses, we are done. Preserve the message log if so configured, and we are using them. Otherwise, sling it. Then delete the message itself. *\/ if (!addr_defer) { uschar * fname; if (message_logs) { fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); if (preserve_message_logs) { int rc; uschar * moname = spool_fname(US\"msglog.OLD\", US\"\", id, US\"\"); if ((rc = Urename(fname, moname)) < 0) { (void)directory_make(spool_directory, spool_sname(US\"msglog.OLD\", US\"\"), MSGLOG_DIRECTORY_MODE, TRUE); rc = Urename(fname, moname); } if (rc < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to move %s to the \" \"msglog.OLD directory\", fname); } else if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); } \/* Remove the two message files. *\/ fname = spool_fname(US\"input\", message_subdir, id, US\"-D\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); fname = spool_fname(US\"input\", message_subdir, id, US\"-H\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Log the end of this message, with queue time if requested. *\/ if (LOGGING(queue_time_overall)) log_write(0, LOG_MAIN, \"Completed QT=%s\", string_timesince(&received_time)); else log_write(0, LOG_MAIN, \"Completed\"); \/* Unset deliver_freeze so that we won't try to move the spool files further down *\/ f.deliver_freeze = FALSE; #ifndef DISABLE_EVENT (void) event_raise(event_action, US\"msg:complete\", NULL); #endif } \/* If there are deferred addresses, we are keeping this message because it is not yet completed. Lose any temporary files that were catching output from pipes for any of the deferred addresses, handle one-time aliases, and see if the message has been on the queue for so long that it is time to send a warning message to the sender, unless it is a mailer-daemon. If all deferred addresses have the same domain, we can set deliver_domain for the expansion of delay_warning_ condition - if any of them are pipes, files, or autoreplies, use the parent's domain. If all the deferred addresses have an error number that indicates \"retry time not reached\", skip sending the warning message, because it won't contain the reason for the delay. It will get sent at the next real delivery attempt. However, if at least one address has tried, we'd better include all of them in the message. If we can't make a process to send the message, don't worry. For mailing list expansions we want to send the warning message to the mailing list manager. We can't do a perfect job here, as some addresses may have different errors addresses, but if we take the errors address from each deferred address it will probably be right in most cases. If addr_defer == +1, it means there was a problem sending an error message for failed addresses, and there were no \"real\" deferred addresses. The value was set just to keep the message on the spool, so there is nothing to do here. *\/ else if (addr_defer != (address_item *)(+1)) { address_item *addr; uschar *recipients = US\"\"; BOOL delivery_attempted = FALSE; deliver_domain = testflag(addr_defer, af_pfr) ? addr_defer->parent->domain : addr_defer->domain; for (addr = addr_defer; addr; addr = addr->next) { address_item *otaddr; if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE; if (deliver_domain) { const uschar *d = testflag(addr, af_pfr) ? addr->parent->domain : addr->domain; \/* The domain may be unset for an address that has never been routed because the system filter froze the message. *\/ if (!d || Ustrcmp(d, deliver_domain) != 0) deliver_domain = NULL; } if (addr->return_filename) Uunlink(addr->return_filename); \/* Handle the case of one-time aliases. If any address in the ancestry of this one is flagged, ensure it is in the recipients list, suitably flagged, and that its parent is marked delivered. *\/ for (otaddr = addr; otaddr; otaddr = otaddr->parent) if (otaddr->onetime_parent) break; if (otaddr) { int i; int t = recipients_count; for (i = 0; i < recipients_count; i++) { uschar *r = recipients_list[i].address; if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i; if (Ustrcmp(otaddr->address, r) == 0) break; } \/* Didn't find the address already in the list, and did find the ultimate parent's address in the list, and they really are different (i.e. not from an identity-redirect). After adding the recipient, update the errors address in the recipients list. *\/ if ( i >= recipients_count && t < recipients_count && Ustrcmp(otaddr->address, otaddr->parent->address) != 0) { DEBUG(D_deliver) debug_printf(\"one_time: adding %s in place of %s\\n\", otaddr->address, otaddr->parent->address); receive_add_recipient(otaddr->address, t); recipients_list[recipients_count-1].errors_to = otaddr->prop.errors_address; tree_add_nonrecipient(otaddr->parent->address); update_spool = TRUE; } } \/* Except for error messages, ensure that either the errors address for this deferred address or, if there is none, the sender address, is on the list of recipients for a warning message. *\/ if (sender_address[0]) { uschar * s = addr->prop.errors_address; if (!s) s = sender_address; if (Ustrstr(recipients, s) == NULL) recipients = string_sprintf(\"%s%s%s\", recipients, recipients[0] ? \",\" : \"\", s); } } \/* Send a warning message if the conditions are right. If the condition check fails because of a lookup defer, there is nothing we can do. The warning is not sent. Another attempt will be made at the next delivery attempt (if it also defers). *\/ if ( !f.queue_2stage && delivery_attempted && ( ((addr_defer->dsn_flags & rf_dsnflags) == 0) || (addr_defer->dsn_flags & rf_notify_delay) == rf_notify_delay ) && delay_warning[1] > 0 && sender_address[0] != 0 && ( !delay_warning_condition || expand_check_condition(delay_warning_condition, US\"delay_warning\", US\"option\") ) ) { int count; int show_time; int queue_time = time(NULL) - received_time.tv_sec; \/* When running in the test harness, there's an option that allows us to fudge this time so as to get repeatability of the tests. Take the first time off the list. In queue runs, the list pointer gets updated in the calling process. *\/ if (f.running_in_test_harness && fudged_queue_times[0] != 0) { int qt = readconf_readtime(fudged_queue_times, '\/', FALSE); if (qt >= 0) { DEBUG(D_deliver) debug_printf(\"fudged queue_times = %s\\n\", fudged_queue_times); queue_time = qt; } } \/* See how many warnings we should have sent by now *\/ for (count = 0; count < delay_warning[1]; count++) if (queue_time < delay_warning[count+2]) break; show_time = delay_warning[count+1]; if (count >= delay_warning[1]) { int extra; int last_gap = show_time; if (count > 1) last_gap -= delay_warning[count]; extra = (queue_time - delay_warning[count+1])\/last_gap; show_time += last_gap * extra; count += extra; } DEBUG(D_deliver) { debug_printf(\"time on queue = %s\\n\", readconf_printtime(queue_time)); debug_printf(\"warning counts: required %d done %d\\n\", count, warning_count); } \/* We have computed the number of warnings there should have been by now. If there haven't been enough, send one, and up the count to what it should have been. *\/ if (warning_count < count) { header_line *h; int fd; pid_t pid = child_open_exim(&fd); if (pid > 0) { uschar *wmf_text; FILE *wmf = NULL; FILE *f = fdopen(fd, \"wb\"); uschar * bound; transport_ctx tctx = {{0}}; if (warn_message_file) if (!(wmf = Ufopen(warn_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for warning \" \"message texts: %s\", warn_message_file, strerror(errno)); warnmsg_recipients = recipients; warnmsg_delay = queue_time < 120*60 ? string_sprintf(\"%d minutes\", show_time\/60) : string_sprintf(\"%d hours\", show_time\/3600); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(f); fprintf(f, \"To: %s\\n\", recipients); \/* generated boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(f, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); if ((wmf_text = next_emf(wmf, US\"header\"))) fprintf(f, \"%s\\n\", wmf_text); else fprintf(f, \"Subject: Warning: message %s delayed %s\\n\\n\", message_id, warnmsg_delay); \/* output human readable part as text\/plain section *\/ fprintf(f, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((wmf_text = next_emf(wmf, US\"intro\"))) fprintf(f, \"%s\", CS wmf_text); else { fprintf(f, \"This message was created automatically by mail delivery software.\\n\"); if (Ustrcmp(recipients, sender_address) == 0) fprintf(f, \"A message that you sent has not yet been delivered to one or more of its\\n\" \"recipients after more than \"); else fprintf(f, \"A message sent by\\n\\n <%s>\\n\\n\" \"has not yet been delivered to one or more of its recipients after more than \\n\", sender_address); fprintf(f, \"%s on the queue on %s.\\n\\n\" \"The message identifier is: %s\\n\", warnmsg_delay, primary_hostname, message_id); for (h = header_list; h; h = h->next) if (strncmpic(h->text, US\"Subject:\", 8) == 0) fprintf(f, \"The subject of the message is: %s\", h->text + 9); else if (strncmpic(h->text, US\"Date:\", 5) == 0) fprintf(f, \"The date of the message is: %s\", h->text + 6); fputc('\\n', f); fprintf(f, \"The address%s to which the message has not yet been \" \"delivered %s:\\n\", !addr_defer->next ? \"\" : \"es\", !addr_defer->next ? \"is\": \"are\"); } \/* List the addresses, with error information if allowed *\/ \/* store addr_defer for machine readable part *\/ address_item *addr_dsndefer = addr_defer; fputc('\\n', f); while (addr_defer) { address_item *addr = addr_defer; addr_defer = addr->next; if (print_address_information(addr, f, US\" \", US\"\\n \", US\"\")) print_address_error(addr, f, US\"Delay reason: \"); fputc('\\n', f); } fputc('\\n', f); \/* Final text *\/ if (wmf) { if ((wmf_text = next_emf(wmf, US\"final\"))) fprintf(f, \"%s\", CS wmf_text); (void)fclose(wmf); } else { fprintf(f, \"No action is required on your part. Delivery attempts will continue for\\n\" \"some time, and this warning may be repeated at intervals if the message\\n\" \"remains undelivered. Eventually the mail delivery software will give up,\\n\" \"and when that happens, the message will be returned to you.\\n\"); } \/* output machine readable part *\/ fprintf(f, \"\\n--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f,\"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f,\"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for ( ; addr_dsndefer; addr_dsndefer = addr_dsndefer->next) { if (addr_dsndefer->dsn_orcpt) fprintf(f, \"Original-Recipient: %s\\n\", addr_dsndefer->dsn_orcpt); fprintf(f, \"Action: delayed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 4.0.0\\n\", addr_dsndefer->address); if (addr_dsndefer->host_used && addr_dsndefer->host_used->name) { fprintf(f, \"Remote-MTA: dns; %s\\n\", addr_dsndefer->host_used->name); print_dsn_diagnostic_code(addr_dsndefer, f); } fputc('\\n', f); } fprintf(f, \"--%s\\n\" \"Content-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); \/* Close and wait for child process to complete, without a timeout. If there's an error, don't update the count. *\/ (void)fclose(f); if (child_close(pid, 0) == 0) { warning_count = count; update_spool = TRUE; \/* Ensure spool rewritten *\/ } } } } \/* Clear deliver_domain *\/ deliver_domain = NULL; \/* If this was a first delivery attempt, unset the first time flag, and ensure that the spool gets updated. *\/ if (f.deliver_firsttime) { f.deliver_firsttime = FALSE; update_spool = TRUE; } \/* If delivery was frozen and freeze_tell is set, generate an appropriate message, unless the message is a local error message (to avoid loops). Then log the freezing. If the text in \"frozen_info\" came from a system filter, it has been escaped into printing characters so as not to mess up log lines. For the \"tell\" message, we turn \\n back into newline. Also, insert a newline near the start instead of the \": \" string. *\/ if (f.deliver_freeze) { if (freeze_tell && freeze_tell[0] != 0 && !f.local_error_message) { uschar *s = string_copy(frozen_info); uschar *ss = Ustrstr(s, \" by the system filter: \"); if (ss != NULL) { ss[21] = '.'; ss[22] = '\\n'; } ss = s; while (*ss != 0) { if (*ss == '\\\\' && ss[1] == 'n') { *ss++ = ' '; *ss++ = '\\n'; } else ss++; } moan_tell_someone(freeze_tell, addr_defer, US\"Message frozen\", \"Message %s has been frozen%s.\\nThe sender is <%s>.\\n\", message_id, s, sender_address); } \/* Log freezing just before we update the -H file, to minimize the chance of a race problem. *\/ deliver_msglog(\"*** Frozen%s\\n\", frozen_info); log_write(0, LOG_MAIN, \"Frozen%s\", frozen_info); } \/* If there have been any updates to the non-recipients list, or other things that get written to the spool, we must now update the spool header file so that it has the right information for the next delivery attempt. If there was more than one address being delivered, the header_change update is done earlier, in case one succeeds and then something crashes. *\/ DEBUG(D_deliver) debug_printf(\"delivery deferred: update_spool=%d header_rewritten=%d\\n\", update_spool, f.header_rewritten); if (update_spool || f.header_rewritten) \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Finished with the message log. If the message is complete, it will have been unlinked or renamed above. *\/ if (message_logs) (void)fclose(message_log); \/* Now we can close and remove the journal file. Its only purpose is to record successfully completed deliveries asap so that this information doesn't get lost if Exim (or the machine) crashes. Forgetting about a failed delivery is not serious, as trying it again is not harmful. The journal might not be open if all addresses were deferred at routing or directing. Nevertheless, we must remove it if it exists (may have been lying around from a crash during the previous delivery attempt). We don't remove the journal if a delivery subprocess failed to pass back delivery information; this is controlled by the remove_journal flag. When the journal is left, we also don't move the message off the main spool if frozen and the option is set. It should get moved at the next attempt, after the journal has been inspected. *\/ if (journal_fd >= 0) (void)close(journal_fd); if (remove_journal) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if (Uunlink(fname) < 0 && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Move the message off the spool if requested *\/ #ifdef SUPPORT_MOVE_FROZEN_MESSAGES if (f.deliver_freeze && move_frozen_messages) (void)spool_move_message(id, message_subdir, US\"\", US\"F\"); #endif } \/* Closing the data file frees the lock; if the file has been unlinked it will go away. Otherwise the message becomes available for another process to try delivery. *\/ (void)close(deliver_datafile); deliver_datafile = -1; DEBUG(D_deliver) debug_printf(\"end delivery of %s\\n\", id); \/* It is unlikely that there will be any cached resources, since they are released after routing, and in the delivery subprocesses. However, it's possible for an expansion for something afterwards (for example, expand_check_condition) to do a lookup. We must therefore be sure everything is released. *\/ search_tidyup(); acl_where = ACL_WHERE_UNKNOWN; return final_yield; }","output":{"is_vulnerable":"True","vulnerability_types":["Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"],"explanation":"A flaw was found in Exim versions 4.87 to 4.91 (inclusive). Improper validation of recipient address in deliver_message() function in \/src\/deliver.c may lead to remote command execution.","severity_level":"NoInfo","cwe":"CWE-78","cve":"CVE-2019-10149"}} -{"idx":3079,"input":"yyparse (void *yyscanner, YR_COMPILER* compiler) { \/* The lookahead symbol. *\/ int yychar; \/* The semantic value of the lookahead symbol. *\/ \/* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. *\/ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); \/* Number of syntax errors so far. *\/ int yynerrs; int yystate; \/* Number of tokens to shift before error messages enabled. *\/ int yyerrstatus; \/* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. *\/ \/* The state stack. *\/ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; \/* The semantic value stack. *\/ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; \/* Lookahead token as an internal (translated) token number. *\/ int yytoken = 0; \/* The variables used to return semantic value and location from the action routines. *\/ YYSTYPE yyval; #if YYERROR_VERBOSE \/* Buffer for error messages, and its allocated size. *\/ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) \/* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. *\/ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, \"Starting parse\\n\")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; \/* Cause a token to be read. *\/ goto yysetstate; \/*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*\/ yynewstate: \/* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. *\/ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { \/* Get the current used size of the three stacks, in elements. *\/ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { \/* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. *\/ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; \/* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. *\/ yyoverflow (YY_(\"memory exhausted\"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else \/* no yyoverflow *\/ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else \/* Extend the stack our own way. *\/ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif \/* no yyoverflow *\/ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, \"Stack size increased to %lu\\n\", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, \"Entering state %d\\n\", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; \/*-----------. | yybackup. | `-----------*\/ yybackup: \/* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. *\/ \/* First try to decide what to do without reference to lookahead token. *\/ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; \/* Not known => get a lookahead token if don't already have one. *\/ \/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. *\/ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, \"Reading a token: \")); yychar = yylex (&yylval, yyscanner, compiler); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, \"Now at end of input.\\n\")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT (\"Next token is\", yytoken, &yylval, &yylloc); } \/* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. *\/ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } \/* Count tokens shifted since error; after three, turn off error status. *\/ if (yyerrstatus) yyerrstatus--; \/* Shift the lookahead token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yytoken, &yylval, &yylloc); \/* Discard the shifted token. *\/ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; \/*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*\/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; \/*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*\/ yyreduce: \/* yyn is the number of a rule to reduce with. *\/ yylen = yyr2[yyn]; \/* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. *\/ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 8: #line 230 \"grammar.y\" \/* yacc.c:1646 *\/ { int result = yr_parser_reduce_import(yyscanner, (yyvsp[0].sized_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF(result != ERROR_SUCCESS); } #line 1661 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 9: #line 242 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_RULE* rule = yr_parser_reduce_rule_declaration_phase_1( yyscanner, (int32_t) (yyvsp[-2].integer), (yyvsp[0].c_string)); ERROR_IF(rule == NULL); (yyval.rule) = rule; } #line 1674 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 10: #line 251 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_RULE* rule = (yyvsp[-4].rule); \/\/ rule created in phase 1 rule->tags = (yyvsp[-3].c_string); rule->metas = (yyvsp[-1].meta); rule->strings = (yyvsp[0].string); } #line 1686 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 11: #line 259 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_RULE* rule = (yyvsp[-7].rule); \/\/ rule created in phase 1 compiler->last_result = yr_parser_reduce_rule_declaration_phase_2( yyscanner, rule); yr_free((yyvsp[-8].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1701 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 12: #line 274 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = NULL; } #line 1709 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 13: #line 278 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_META null_meta; memset(&null_meta, 0xFF, sizeof(YR_META)); null_meta.type = META_TYPE_NULL; compiler->last_result = yr_arena_write_data( compiler->metas_arena, &null_meta, sizeof(YR_META), NULL); (yyval.meta) = (yyvsp[0].meta); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1736 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 14: #line 305 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = NULL; } #line 1744 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 15: #line 309 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_STRING null_string; memset(&null_string, 0xFF, sizeof(YR_STRING)); null_string.g_flags = STRING_GFLAGS_NULL; compiler->last_result = yr_arena_write_data( compiler->strings_arena, &null_string, sizeof(YR_STRING), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.string) = (yyvsp[0].string); } #line 1771 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 17: #line 340 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = 0; } #line 1777 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 18: #line 341 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 1783 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 19: #line 346 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = RULE_GFLAGS_PRIVATE; } #line 1789 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 20: #line 347 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = RULE_GFLAGS_GLOBAL; } #line 1795 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 21: #line 353 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = NULL; } #line 1803 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 22: #line 357 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, \"\", NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[0].c_string); } #line 1821 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 23: #line 375 \"grammar.y\" \/* yacc.c:1646 *\/ { char* identifier; compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), &identifier); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = identifier; } #line 1838 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 24: #line 388 \"grammar.y\" \/* yacc.c:1646 *\/ { char* tag_name = (yyvsp[-1].c_string); size_t tag_length = tag_name != NULL ? strlen(tag_name) : 0; while (tag_length > 0) { if (strcmp(tag_name, (yyvsp[0].c_string)) == 0) { yr_compiler_set_error_extra_info(compiler, tag_name); compiler->last_result = ERROR_DUPLICATED_TAG_IDENTIFIER; break; } tag_name = (char*) yr_arena_next_address( yyget_extra(yyscanner)->sz_arena, tag_name, tag_length + 1); tag_length = tag_name != NULL ? strlen(tag_name) : 0; } if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), NULL); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-1].c_string); } #line 1874 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 25: #line 424 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = (yyvsp[0].meta); } #line 1880 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 26: #line 425 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = (yyvsp[-1].meta); } #line 1886 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 27: #line 431 \"grammar.y\" \/* yacc.c:1646 *\/ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_STRING, (yyvsp[-2].c_string), sized_string->c_string, 0); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.meta) == NULL); } #line 1906 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 28: #line 447 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-2].c_string), NULL, (yyvsp[0].integer)); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1923 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 29: #line 460 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-3].c_string), NULL, -(yyvsp[0].integer)); yr_free((yyvsp[-3].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1940 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 30: #line 473 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, TRUE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1957 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 31: #line 486 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, FALSE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1974 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 32: #line 502 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = (yyvsp[0].string); } #line 1980 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 33: #line 503 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = (yyvsp[-1].string); } #line 1986 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 34: #line 509 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->error_line = yyget_lineno(yyscanner); } #line 1994 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 35: #line 513 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer), (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2009 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 36: #line 524 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->error_line = yyget_lineno(yyscanner); } #line 2017 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 37: #line 528 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer) | STRING_GFLAGS_REGEXP, (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2033 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 38: #line 540 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, STRING_GFLAGS_HEXADECIMAL, (yyvsp[-2].c_string), (yyvsp[0].sized_string)); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.string) == NULL); } #line 2047 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 39: #line 553 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = 0; } #line 2053 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 40: #line 554 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 2059 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 41: #line 559 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_WIDE; } #line 2065 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 42: #line 560 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_ASCII; } #line 2071 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 43: #line 561 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_NO_CASE; } #line 2077 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 44: #line 562 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_FULL_WORD; } #line 2083 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 45: #line 568 \"grammar.y\" \/* yacc.c:1646 *\/ { int var_index = yr_parser_lookup_loop_variable(yyscanner, (yyvsp[0].c_string)); if (var_index >= 0) { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, LOOP_LOCAL_VARS * var_index, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = compiler->loop_identifier[var_index]; } else { YR_OBJECT* object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), NULL); if (object == NULL) { char* ns = compiler->current_namespace->name; object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), ns); } if (object != NULL) { char* id; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &id); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_LOAD, id, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = object; (yyval.expression).identifier = object->identifier; } else { YR_RULE* rule = (YR_RULE*) yr_hash_table_lookup( compiler->rules_table, (yyvsp[0].c_string), compiler->current_namespace->name); if (rule != NULL) { compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH_RULE, rule, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = rule->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_UNDEFINED_IDENTIFIER; } } } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2172 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 46: #line 653 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_OBJECT* field = NULL; if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-2].expression).value.object->type == OBJECT_TYPE_STRUCTURE) { field = yr_object_lookup_field((yyvsp[-2].expression).value.object, (yyvsp[0].c_string)); if (field != NULL) { char* ident; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &ident); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_FIELD, ident, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = field; (yyval.expression).identifier = field->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_INVALID_FIELD_NAME; } } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-2].expression).identifier); compiler->last_result = ERROR_NOT_A_STRUCTURE; } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2222 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 47: #line 699 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_OBJECT_ARRAY* array; YR_OBJECT_DICTIONARY* dict; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_ARRAY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"array indexes must be of integer type\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_INDEX_ARRAY, NULL); array = (YR_OBJECT_ARRAY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = array->prototype_item; (yyval.expression).identifier = array->identifier; } else if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_DICTIONARY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_STRING) { yr_compiler_set_error_extra_info( compiler, \"dictionary keys must be of string type\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_LOOKUP_DICT, NULL); dict = (YR_OBJECT_DICTIONARY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = dict->prototype_item; (yyval.expression).identifier = dict->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_INDEXABLE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2283 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 48: #line 757 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_OBJECT_FUNCTION* function; char* args_fmt; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_FUNCTION) { compiler->last_result = yr_parser_check_types( compiler, (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object, (yyvsp[-1].c_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[-1].c_string), &args_fmt); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_CALL, args_fmt, NULL, NULL); function = (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = function->return_obj; (yyval.expression).identifier = function->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_A_FUNCTION; } yr_free((yyvsp[-1].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2328 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 49: #line 801 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = yr_strdup(\"\"); } #line 2334 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 50: #line 802 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = (yyvsp[0].c_string); } #line 2340 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 51: #line 807 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = (char*) yr_malloc(MAX_FUNCTION_ARGS + 1); switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcpy((yyval.c_string), \"i\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcpy((yyval.c_string), \"f\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcpy((yyval.c_string), \"b\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcpy((yyval.c_string), \"s\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcpy((yyval.c_string), \"r\", MAX_FUNCTION_ARGS); break; } ERROR_IF((yyval.c_string) == NULL); } #line 2369 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 52: #line 832 \"grammar.y\" \/* yacc.c:1646 *\/ { if (strlen((yyvsp[-2].c_string)) == MAX_FUNCTION_ARGS) { compiler->last_result = ERROR_TOO_MANY_ARGUMENTS; } else { switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcat((yyvsp[-2].c_string), \"i\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcat((yyvsp[-2].c_string), \"f\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcat((yyvsp[-2].c_string), \"b\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcat((yyvsp[-2].c_string), \"s\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcat((yyvsp[-2].c_string), \"r\", MAX_FUNCTION_ARGS); break; } } ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-2].c_string); } #line 2405 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 53: #line 868 \"grammar.y\" \/* yacc.c:1646 *\/ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); RE* re; RE_ERROR error; int re_flags = 0; if (sized_string->flags & SIZED_STRING_FLAGS_NO_CASE) re_flags |= RE_FLAGS_NO_CASE; if (sized_string->flags & SIZED_STRING_FLAGS_DOT_ALL) re_flags |= RE_FLAGS_DOT_ALL; compiler->last_result = yr_re_compile( sized_string->c_string, re_flags, compiler->re_code_arena, &re, &error); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_INVALID_REGULAR_EXPRESSION) yr_compiler_set_error_extra_info(compiler, error.message); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, re->root_node->forward_code, NULL, NULL); yr_re_destroy(re); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_REGEXP; } #line 2451 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 54: #line 914 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_STRING) { if ((yyvsp[0].expression).value.sized_string != NULL) { yywarning(yyscanner, \"Using literal string \\\"%s\\\" in a boolean operation.\", (yyvsp[0].expression).value.sized_string->c_string); } compiler->last_result = yr_parser_emit( yyscanner, OP_STR_TO_BOOL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2474 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 55: #line 936 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2487 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 56: #line 945 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 0, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2500 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 57: #line 954 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, \"matches\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_REGEXP, \"matches\"); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit( yyscanner, OP_MATCHES, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2519 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 58: #line 969 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, \"contains\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_STRING, \"contains\"); compiler->last_result = yr_parser_emit( yyscanner, OP_CONTAINS, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2535 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 59: #line 981 \"grammar.y\" \/* yacc.c:1646 *\/ { int result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_FOUND, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2553 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 60: #line 995 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"at\"); compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_AT, (yyvsp[0].expression).value.integer); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2570 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 61: #line 1008 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_IN, UNDEFINED); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result!= ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2585 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 62: #line 1019 \"grammar.y\" \/* yacc.c:1646 *\/ { int var_index; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \\ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; ERROR_IF(compiler->last_result != ERROR_SUCCESS); var_index = yr_parser_lookup_loop_variable( yyscanner, (yyvsp[-1].c_string)); if (var_index >= 0) { yr_compiler_set_error_extra_info( compiler, (yyvsp[-1].c_string)); compiler->last_result = \\ ERROR_DUPLICATED_LOOP_IDENTIFIER; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2619 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 63: #line 1049 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-1].integer) == INTEGER_SET_ENUMERATION) { yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); } else \/\/ INTEGER_SET_RANGE { yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset + 3, &addr, NULL); yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, NULL, NULL); } compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = (yyvsp[-4].c_string); compiler->loop_depth++; } #line 2658 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 64: #line 1084 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset; compiler->loop_depth--; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-5].integer) == INTEGER_SET_ENUMERATION) { yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); } else \/\/ INTEGER_SET_RANGE { yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 3, NULL, NULL); yr_parser_emit_with_arg_reloc( yyscanner, OP_JLE, compiler->loop_address[compiler->loop_depth], NULL, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); } yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); compiler->loop_identifier[compiler->loop_depth] = NULL; yr_free((yyvsp[-8].c_string)); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2741 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 65: #line 1163 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \\ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; if (compiler->loop_for_of_mem_offset != -1) compiler->last_result = \\ ERROR_NESTED_FOR_OF_LOOP; ERROR_IF(compiler->last_result != ERROR_SUCCESS); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); compiler->loop_for_of_mem_offset = mem_offset; compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = NULL; compiler->loop_depth++; } #line 2775 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 66: #line 1193 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset; compiler->loop_depth--; compiler->loop_for_of_mem_offset = -1; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2828 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 67: #line 1242 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit(yyscanner, OP_OF, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2838 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 68: #line 1248 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit(yyscanner, OP_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2848 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 69: #line 1254 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JFALSE, 0, \/\/ still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2878 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 70: #line 1280 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; uint8_t* and_addr; compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_AND, &and_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = compiler->fixup_stack_head; *(void**)(fixup->address) = (void*)(and_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2918 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 71: #line 1316 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JTRUE, 0, \/\/ still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2947 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 72: #line 1341 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; uint8_t* or_addr; compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_OR, &or_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = compiler->fixup_stack_head; *(void**)(fixup->address) = (void*)(or_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2987 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 73: #line 1377 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"<\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3000 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 74: #line 1386 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \">\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3013 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 75: #line 1395 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"<=\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3026 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 76: #line 1404 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \">=\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3039 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 77: #line 1413 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"==\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3052 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 78: #line 1422 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"!=\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3065 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 79: #line 1431 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[0].expression); } #line 3073 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 80: #line 1435 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[-1].expression); } #line 3081 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 81: #line 1442 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = INTEGER_SET_ENUMERATION; } #line 3087 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 82: #line 1443 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = INTEGER_SET_RANGE; } #line 3093 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 83: #line 1449 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[-3].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for range's lower bound\"); compiler->last_result = ERROR_WRONG_TYPE; } if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for range's upper bound\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3115 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 84: #line 1471 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for enumeration item\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3131 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 85: #line 1483 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for enumeration item\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3146 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 86: #line 1498 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3155 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 88: #line 1504 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); yr_parser_emit_pushes_for_strings(yyscanner, \"$*\"); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3166 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 91: #line 1521 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3177 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 92: #line 1528 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3188 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 94: #line 1540 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3196 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 95: #line 1544 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL); } #line 3204 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 96: #line 1552 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[-1].expression); } #line 3212 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 97: #line 1556 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit( yyscanner, OP_FILESIZE, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3226 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 98: #line 1566 \"grammar.y\" \/* yacc.c:1646 *\/ { yywarning(yyscanner, \"Using deprecated \\\"entrypoint\\\" keyword. Use the \\\"entry_point\\\" \" \"function from PE module instead.\"); compiler->last_result = yr_parser_emit( yyscanner, OP_ENTRYPOINT, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3244 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 99: #line 1580 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-1].expression), EXPRESSION_TYPE_INTEGER, \"intXXXX or uintXXXX\"); compiler->last_result = yr_parser_emit( yyscanner, (uint8_t) (OP_READ_INT + (yyvsp[-3].integer)), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3264 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 100: #line 1596 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, (yyvsp[0].integer), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = (yyvsp[0].integer); } #line 3278 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 101: #line 1606 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg_double( yyscanner, OP_PUSH, (yyvsp[0].double_), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } #line 3291 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 102: #line 1615 \"grammar.y\" \/* yacc.c:1646 *\/ { SIZED_STRING* sized_string; compiler->last_result = yr_arena_write_data( compiler->sz_arena, (yyvsp[0].sized_string), (yyvsp[0].sized_string)->length + sizeof(SIZED_STRING), (void**) &sized_string); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, sized_string, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = sized_string; } #line 3320 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 103: #line 1640 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_COUNT, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3336 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 104: #line 1652 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3352 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 105: #line 1664 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3372 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 106: #line 1680 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3388 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 107: #line 1692 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3408 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 108: #line 1708 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) \/\/ loop identifier { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_BOOLEAN) \/\/ rule identifier { (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_OBJECT) { compiler->last_result = yr_parser_emit( yyscanner, OP_OBJ_VALUE, NULL); switch((yyvsp[0].expression).value.object->type) { case OBJECT_TYPE_INTEGER: (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; break; case OBJECT_TYPE_FLOAT: (yyval.expression).type = EXPRESSION_TYPE_FLOAT; break; case OBJECT_TYPE_STRING: (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = NULL; break; default: yr_compiler_set_error_extra_info_fmt( compiler, \"wrong usage of identifier \\\"%s\\\"\", (yyvsp[0].expression).identifier); compiler->last_result = ERROR_WRONG_TYPE; } } else { assert(FALSE); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3457 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 109: #line 1753 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT, \"-\"); if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : -((yyvsp[0].expression).value.integer); compiler->last_result = yr_parser_emit(yyscanner, OP_INT_MINUS, NULL); } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_FLOAT) { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; compiler->last_result = yr_parser_emit(yyscanner, OP_DBL_MINUS, NULL); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3480 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 110: #line 1772 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"+\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(+, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3502 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 111: #line 1790 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"-\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(-, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3524 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 112: #line 1808 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"*\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(*, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3546 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 113: #line 1826 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"\\\\\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(\/, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3576 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 114: #line 1852 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"%\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"%\"); yr_parser_emit(yyscanner, OP_MOD, NULL); if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(%, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } #line 3598 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 115: #line 1870 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"^\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"^\"); yr_parser_emit(yyscanner, OP_BITWISE_XOR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(^, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3612 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 116: #line 1880 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"^\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"^\"); yr_parser_emit(yyscanner, OP_BITWISE_AND, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(&, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3626 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 117: #line 1890 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"|\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"|\"); yr_parser_emit(yyscanner, OP_BITWISE_OR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(|, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3640 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 118: #line 1900 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"~\"); yr_parser_emit(yyscanner, OP_BITWISE_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : ~((yyvsp[0].expression).value.integer); } #line 3654 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 119: #line 1910 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"<<\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"<<\"); yr_parser_emit(yyscanner, OP_SHL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(<<, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3668 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 120: #line 1920 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \">>\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \">>\"); yr_parser_emit(yyscanner, OP_SHR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(>>, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3682 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 121: #line 1930 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[0].expression); } #line 3690 \"grammar.c\" \/* yacc.c:1646 *\/ break; #line 3694 \"grammar.c\" \/* yacc.c:1646 *\/ default: break; } \/* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. *\/ YY_SYMBOL_PRINT (\"-> $$ =\", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; \/* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. *\/ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; \/*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*\/ yyerrlab: \/* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. *\/ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); \/* If not already recovering from an error, report this error. *\/ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (yyscanner, compiler, YY_(\"syntax error\")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \\ yyssp, yytoken) { char const *yymsgp = YY_(\"syntax error\"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yyscanner, compiler, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { \/* If just tried and failed to reuse lookahead token after an error, discard it. *\/ if (yychar <= YYEOF) { \/* Return failure if at end of input. *\/ if (yychar == YYEOF) YYABORT; } else { yydestruct (\"Error: discarding\", yytoken, &yylval, yyscanner, compiler); yychar = YYEMPTY; } } \/* Else will try to reuse lookahead token after shifting the error token. *\/ goto yyerrlab1; \/*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*\/ yyerrorlab: \/* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. *\/ if (\/*CONSTCOND*\/ 0) goto yyerrorlab; \/* Do not reclaim the symbols of the rule whose action triggered this YYERROR. *\/ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; \/*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*\/ yyerrlab1: yyerrstatus = 3; \/* Each real token shifted decrements this. *\/ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } \/* Pop the current state because it cannot handle the error token. *\/ if (yyssp == yyss) YYABORT; yydestruct (\"Error: popping\", yystos[yystate], yyvsp, yyscanner, compiler); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END \/* Shift the error token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; \/*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*\/ yyacceptlab: yyresult = 0; goto yyreturn; \/*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*\/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE \/*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*\/ yyexhaustedlab: yyerror (yyscanner, compiler, YY_(\"memory exhausted\")); yyresult = 2; \/* Fall through. *\/ #endif yyreturn: if (yychar != YYEMPTY) { \/* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. *\/ yytoken = YYTRANSLATE (yychar); yydestruct (\"Cleanup: discarding lookahead\", yytoken, &yylval, yyscanner, compiler); } \/* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. *\/ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct (\"Cleanup: popping\", yystos[*yyssp], yyvsp, yyscanner, compiler); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; }","output":{"is_vulnerable":"True","vulnerability_types":["Use After Free"],"explanation":"libyara\/re.c in the regex component in YARA 3.5.0 allows remote attackers to cause a denial of service (out-of-bounds read and application crash) via a crafted rule that is mishandled in the yr_re_exec function.","severity_level":"Medium","cwe":"CWE-416","cve":"CVE-2017-8294"}} -{"idx":81050,"input":"WandExport MagickBooleanType MogrifyImageCommand(ImageInfo *image_info, int argc,char **argv,char **wand_unused(metadata),ExceptionInfo *exception) { #define DestroyMogrify() \\ { \\ if (format != (char *) NULL) \\ format=DestroyString(format); \\ if (path != (char *) NULL) \\ path=DestroyString(path); \\ DestroyImageStack(); \\ for (i=0; i < (ssize_t) argc; i++) \\ argv[i]=DestroyString(argv[i]); \\ argv=(char **) RelinquishMagickMemory(argv); \\ } #define ThrowMogrifyException(asperity,tag,option) \\ { \\ (void) ThrowMagickException(exception,GetMagickModule(),asperity,tag,\"`%s'\", \\ option); \\ DestroyMogrify(); \\ return(MagickFalse); \\ } #define ThrowMogrifyInvalidArgumentException(option,argument) \\ { \\ (void) ThrowMagickException(exception,GetMagickModule(),OptionError, \\ \"InvalidArgument\",\"`%s': %s\",argument,option); \\ DestroyMogrify(); \\ return(MagickFalse); \\ } char *format, *option, *path; Image *image; ImageStack image_stack[MaxImageStackDepth+1]; MagickBooleanType global_colormap; MagickBooleanType fire, pend, respect_parenthesis; MagickStatusType status; register ssize_t i; ssize_t j, k; wand_unreferenced(metadata); \/* Set defaults. *\/ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\"); assert(exception != (ExceptionInfo *) NULL); if (argc == 2) { option=argv[1]; if ((LocaleCompare(\"version\",option+1) == 0) || (LocaleCompare(\"-version\",option+1) == 0)) { ListMagickVersion(stdout); return(MagickTrue); } } if (argc < 2) return(MogrifyUsage()); format=(char *) NULL; path=(char *) NULL; global_colormap=MagickFalse; k=0; j=1; NewImageStack(); option=(char *) NULL; pend=MagickFalse; respect_parenthesis=MagickFalse; status=MagickTrue; \/* Parse command line. *\/ ReadCommandlLine(argc,&argv); status=ExpandFilenames(&argc,&argv); if (status == MagickFalse) ThrowMogrifyException(ResourceLimitError,\"MemoryAllocationFailed\", GetExceptionMessage(errno)); for (i=1; i < (ssize_t) argc; i++) { option=argv[i]; if (LocaleCompare(option,\"(\") == 0) { FireImageStack(MagickFalse,MagickTrue,pend); if (k == MaxImageStackDepth) ThrowMogrifyException(OptionError,\"ParenthesisNestedTooDeeply\", option); PushImageStack(); continue; } if (LocaleCompare(option,\")\") == 0) { FireImageStack(MagickFalse,MagickTrue,MagickTrue); if (k == 0) ThrowMogrifyException(OptionError,\"UnableToParseExpression\",option); PopImageStack(); continue; } if (IsCommandOption(option) == MagickFalse) { char backup_filename[MaxTextExtent], *filename; Image *images; struct stat properties; \/* Option is a file name: begin by reading image from specified file. *\/ FireImageStack(MagickFalse,MagickFalse,pend); filename=argv[i]; if ((LocaleCompare(filename,\"--\") == 0) && (i < (ssize_t) (argc-1))) filename=argv[++i]; (void) SetImageOption(image_info,\"filename\",filename); (void) CopyMagickString(image_info->filename,filename,MaxTextExtent); images=ReadImages(image_info,exception); status&=(images != (Image *) NULL) && (exception->severity < ErrorException); if (images == (Image *) NULL) continue; properties=(*GetBlobProperties(images)); if (format != (char *) NULL) (void) CopyMagickString(images->filename,images->magick_filename, MaxTextExtent); if (path != (char *) NULL) { GetPathComponent(option,TailPath,filename); (void) FormatLocaleString(images->filename,MaxTextExtent,\"%s%c%s\", path,*DirectorySeparator,filename); } if (format != (char *) NULL) AppendImageFormat(format,images->filename); AppendImageStack(images); FinalizeImageSettings(image_info,image,MagickFalse); if (global_colormap != MagickFalse) { QuantizeInfo *quantize_info; quantize_info=AcquireQuantizeInfo(image_info); (void) RemapImages(quantize_info,images,(Image *) NULL); quantize_info=DestroyQuantizeInfo(quantize_info); } *backup_filename='\\0'; if ((LocaleCompare(image->filename,\"-\") != 0) && (IsPathWritable(image->filename) != MagickFalse)) { register ssize_t i; \/* Rename image file as backup. *\/ (void) CopyMagickString(backup_filename,image->filename, MaxTextExtent); for (i=0; i < 6; i++) { (void) ConcatenateMagickString(backup_filename,\"~\",MaxTextExtent); if (IsPathAccessible(backup_filename) == MagickFalse) break; } if ((IsPathAccessible(backup_filename) != MagickFalse) || (rename_utf8(image->filename,backup_filename) != 0)) *backup_filename='\\0'; } \/* Write transmogrified image to disk. *\/ image_info->synchronize=MagickTrue; status&=WriteImages(image_info,image,image->filename,exception); if (status != MagickFalse) { #if defined(MAGICKCORE_HAVE_UTIME) { MagickBooleanType preserve_timestamp; preserve_timestamp=IsStringTrue(GetImageOption(image_info, \"preserve-timestamp\")); if (preserve_timestamp != MagickFalse) { struct utimbuf timestamp; timestamp.actime=properties.st_atime; timestamp.modtime=properties.st_mtime; (void) utime(image->filename,×tamp); } } #endif if (*backup_filename != '\\0') (void) remove_utf8(backup_filename); } RemoveAllImageStack(); continue; } pend=image != (Image *) NULL ? MagickTrue : MagickFalse; switch (*(option+1)) { case 'a': { if (LocaleCompare(\"adaptive-blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"adaptive-resize\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"adaptive-sharpen\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"affine\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"alpha\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickAlphaOptions,MagickFalse,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedAlphaChannelType\", argv[i]); break; } if (LocaleCompare(\"annotate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); i++; break; } if (LocaleCompare(\"antialias\",option+1) == 0) break; if (LocaleCompare(\"append\",option+1) == 0) break; if (LocaleCompare(\"attenuate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"authenticate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"auto-gamma\",option+1) == 0) break; if (LocaleCompare(\"auto-level\",option+1) == 0) break; if (LocaleCompare(\"auto-orient\",option+1) == 0) break; if (LocaleCompare(\"average\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'b': { if (LocaleCompare(\"background\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"bias\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"black-point-compensation\",option+1) == 0) break; if (LocaleCompare(\"black-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"blue-primary\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"blue-shift\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"border\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"bordercolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"box\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"brightness-contrast\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'c': { if (LocaleCompare(\"cache\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"canny\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"caption\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"channel\",option+1) == 0) { ssize_t channel; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); channel=ParseChannelOption(argv[i]); if (channel < 0) ThrowMogrifyException(OptionError,\"UnrecognizedChannelType\", argv[i]); break; } if (LocaleCompare(\"cdl\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"charcoal\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"chop\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"clamp\",option+1) == 0) break; if (LocaleCompare(\"clip\",option+1) == 0) break; if (LocaleCompare(\"clip-mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"clut\",option+1) == 0) break; if (LocaleCompare(\"coalesce\",option+1) == 0) break; if (LocaleCompare(\"colorize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"color-matrix\",option+1) == 0) { KernelInfo *kernel_info; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); kernel_info=AcquireKernelInfo(argv[i]); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"colors\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"colorspace\",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedColorspace\", argv[i]); break; } if (LocaleCompare(\"combine\",option+1) == 0) { if (*option == '-') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"comment\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"compare\",option+1) == 0) break; if (LocaleCompare(\"complex\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickComplexOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedComplexOperator\", argv[i]); break; } if (LocaleCompare(\"composite\",option+1) == 0) break; if (LocaleCompare(\"compress\",option+1) == 0) { ssize_t compress; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); compress=ParseCommandOption(MagickCompressOptions,MagickFalse, argv[i]); if (compress < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageCompression\", argv[i]); break; } if (LocaleCompare(\"concurrent\",option+1) == 0) break; if (LocaleCompare(\"connected-components\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"contrast\",option+1) == 0) break; if (LocaleCompare(\"contrast-stretch\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"convolve\",option+1) == 0) { KernelInfo *kernel_info; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); kernel_info=AcquireKernelInfo(argv[i]); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"copy\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"crop\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"cycle\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'd': { if (LocaleCompare(\"decipher\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"deconstruct\",option+1) == 0) break; if (LocaleCompare(\"debug\",option+1) == 0) { ssize_t event; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); event=ParseCommandOption(MagickLogEventOptions,MagickFalse,argv[i]); if (event < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEventType\", argv[i]); (void) SetLogEventMask(argv[i]); break; } if (LocaleCompare(\"define\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (*option == '+') { const char *define; define=GetImageOption(image_info,argv[i]); if (define == (const char *) NULL) ThrowMogrifyException(OptionError,\"NoSuchOption\",argv[i]); break; } break; } if (LocaleCompare(\"delay\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"delete\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"density\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"depth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"deskew\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"despeckle\",option+1) == 0) break; if (LocaleCompare(\"dft\",option+1) == 0) break; if (LocaleCompare(\"direction\",option+1) == 0) { ssize_t direction; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, argv[i]); if (direction < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDirectionType\", argv[i]); break; } if (LocaleCompare(\"display\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"dispose\",option+1) == 0) { ssize_t dispose; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, argv[i]); if (dispose < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDisposeMethod\", argv[i]); break; } if (LocaleCompare(\"distort\",option+1) == 0) { ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickDistortOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDistortMethod\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"dither\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickDitherOptions,MagickFalse,argv[i]); if (method < 0) ThrowMogrifyException(OptionError,\"UnrecognizedDitherMethod\", argv[i]); break; } if (LocaleCompare(\"draw\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"duplicate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"duration\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'e': { if (LocaleCompare(\"edge\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"emboss\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"encipher\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"encoding\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"endian\",option+1) == 0) { ssize_t endian; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); endian=ParseCommandOption(MagickEndianOptions,MagickFalse,argv[i]); if (endian < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEndianType\", argv[i]); break; } if (LocaleCompare(\"enhance\",option+1) == 0) break; if (LocaleCompare(\"equalize\",option+1) == 0) break; if (LocaleCompare(\"evaluate\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEvaluateOperator\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"evaluate-sequence\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedEvaluateOperator\", argv[i]); break; } if (LocaleCompare(\"extent\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"extract\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'f': { if (LocaleCompare(\"family\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"features\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"fill\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"filter\",option+1) == 0) { ssize_t filter; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); filter=ParseCommandOption(MagickFilterOptions,MagickFalse,argv[i]); if (filter < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageFilter\", argv[i]); break; } if (LocaleCompare(\"flatten\",option+1) == 0) break; if (LocaleCompare(\"flip\",option+1) == 0) break; if (LocaleCompare(\"flop\",option+1) == 0) break; if (LocaleCompare(\"floodfill\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"font\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"format\",option+1) == 0) { (void) CopyMagickString(argv[i]+1,\"sans\",MaxTextExtent); (void) CloneString(&format,(char *) NULL); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); (void) CloneString(&format,argv[i]); (void) CopyMagickString(image_info->filename,format,MaxTextExtent); (void) ConcatenateMagickString(image_info->filename,\":\", MaxTextExtent); (void) SetImageInfo(image_info,0,exception); if (*image_info->magick == '\\0') ThrowMogrifyException(OptionError,\"UnrecognizedImageFormat\", format); break; } if (LocaleCompare(\"frame\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"function\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickFunctionOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedFunction\",argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"fuzz\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"fx\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'g': { if (LocaleCompare(\"gamma\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if ((LocaleCompare(\"gaussian-blur\",option+1) == 0) || (LocaleCompare(\"gaussian\",option+1) == 0)) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"geometry\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"gravity\",option+1) == 0) { ssize_t gravity; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse, argv[i]); if (gravity < 0) ThrowMogrifyException(OptionError,\"UnrecognizedGravityType\", argv[i]); break; } if (LocaleCompare(\"grayscale\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickPixelIntensityOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError,\"UnrecognizedIntensityMethod\", argv[i]); break; } if (LocaleCompare(\"green-primary\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'h': { if (LocaleCompare(\"hald-clut\",option+1) == 0) break; if (LocaleCompare(\"hough-lines\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if ((LocaleCompare(\"help\",option+1) == 0) || (LocaleCompare(\"-help\",option+1) == 0)) return(MogrifyUsage()); ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'i': { if (LocaleCompare(\"identify\",option+1) == 0) break; if (LocaleCompare(\"idft\",option+1) == 0) break; if (LocaleCompare(\"implode\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"intensity\",option+1) == 0) { ssize_t intensity; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,argv[i]); if (intensity < 0) ThrowMogrifyException(OptionError, \"UnrecognizedPixelIntensityMethod\",argv[i]); break; } if (LocaleCompare(\"intent\",option+1) == 0) { ssize_t intent; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); intent=ParseCommandOption(MagickIntentOptions,MagickFalse,argv[i]); if (intent < 0) ThrowMogrifyException(OptionError,\"UnrecognizedIntentType\", argv[i]); break; } if (LocaleCompare(\"interlace\",option+1) == 0) { ssize_t interlace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); interlace=ParseCommandOption(MagickInterlaceOptions,MagickFalse, argv[i]); if (interlace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedInterlaceType\", argv[i]); break; } if (LocaleCompare(\"interline-spacing\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"interpolate\",option+1) == 0) { ssize_t interpolate; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse, argv[i]); if (interpolate < 0) ThrowMogrifyException(OptionError,\"UnrecognizedInterpolateMethod\", argv[i]); break; } if (LocaleCompare(\"interword-spacing\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'k': { if (LocaleCompare(\"kerning\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"kuwahara\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'l': { if (LocaleCompare(\"label\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"lat\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); } if (LocaleCompare(\"layers\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickLayerOptions,MagickFalse,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedLayerMethod\", argv[i]); break; } if (LocaleCompare(\"level\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"level-colors\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"linewidth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"limit\",option+1) == 0) { char *p; double value; ssize_t resource; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); resource=ParseCommandOption(MagickResourceOptions,MagickFalse, argv[i]); if (resource < 0) ThrowMogrifyException(OptionError,\"UnrecognizedResourceType\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); value=StringToDouble(argv[i],&p); (void) value; if ((p == argv[i]) && (LocaleCompare(\"unlimited\",argv[i]) != 0)) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"liquid-rescale\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"list\",option+1) == 0) { ssize_t list; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); list=ParseCommandOption(MagickListOptions,MagickFalse,argv[i]); if (list < 0) ThrowMogrifyException(OptionError,\"UnrecognizedListType\",argv[i]); status=MogrifyImageInfo(image_info,(int) (i-j+1),(const char **) argv+j,exception); return(status == 0 ? MagickFalse : MagickTrue); } if (LocaleCompare(\"local-contrast\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"log\",option+1) == 0) { if (*option == '+') break; i++; if ((i == (ssize_t) argc) || (strchr(argv[i],'%') == (char *) NULL)) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"loop\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'm': { if (LocaleCompare(\"magnify\",option+1) == 0) break; if (LocaleCompare(\"map\",option+1) == 0) { global_colormap=(*option == '+') ? MagickTrue : MagickFalse; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"mask\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"matte\",option+1) == 0) break; if (LocaleCompare(\"mattecolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"metric\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickMetricOptions,MagickTrue,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedMetricType\", argv[i]); break; } if (LocaleCompare(\"maximum\",option+1) == 0) break; if (LocaleCompare(\"mean-shift\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"median\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"minimum\",option+1) == 0) break; if (LocaleCompare(\"modulate\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"mode\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"monitor\",option+1) == 0) break; if (LocaleCompare(\"monochrome\",option+1) == 0) break; if (LocaleCompare(\"morph\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"morphology\",option+1) == 0) { char token[MaxTextExtent]; KernelInfo *kernel_info; ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); GetNextToken(argv[i],(const char **) NULL,MaxTextExtent,token); op=ParseCommandOption(MagickMorphologyOptions,MagickFalse,token); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedMorphologyMethod\", token); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); kernel_info=AcquireKernelInfo(argv[i]); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"mosaic\",option+1) == 0) break; if (LocaleCompare(\"motion-blur\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'n': { if (LocaleCompare(\"negate\",option+1) == 0) break; if (LocaleCompare(\"noise\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (*option == '+') { ssize_t noise; noise=ParseCommandOption(MagickNoiseOptions,MagickFalse,argv[i]); if (noise < 0) ThrowMogrifyException(OptionError,\"UnrecognizedNoiseType\", argv[i]); break; } if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"noop\",option+1) == 0) break; if (LocaleCompare(\"normalize\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'o': { if (LocaleCompare(\"opaque\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"ordered-dither\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"orient\",option+1) == 0) { ssize_t orientation; orientation=UndefinedOrientation; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); orientation=ParseCommandOption(MagickOrientationOptions,MagickFalse, argv[i]); if (orientation < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageOrientation\", argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'p': { if (LocaleCompare(\"page\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"paint\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"path\",option+1) == 0) { (void) CloneString(&path,(char *) NULL); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); (void) CloneString(&path,argv[i]); break; } if (LocaleCompare(\"perceptible\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"pointsize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"polaroid\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"poly\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"posterize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"precision\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"print\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"process\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"profile\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'q': { if (LocaleCompare(\"quality\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"quantize\",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,\"UnrecognizedColorspace\", argv[i]); break; } if (LocaleCompare(\"quiet\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'r': { if (LocaleCompare(\"radial-blur\",option+1) == 0 || LocaleCompare(\"rotational-blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"raise\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"random-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"recolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"red-primary\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); } if (LocaleCompare(\"regard-warnings\",option+1) == 0) break; if (LocaleCompare(\"region\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"remap\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"render\",option+1) == 0) break; if (LocaleCompare(\"repage\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"resample\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"resize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleNCompare(\"respect-parentheses\",option+1,17) == 0) { respect_parenthesis=(*option == '-') ? MagickTrue : MagickFalse; break; } if (LocaleCompare(\"reverse\",option+1) == 0) break; if (LocaleCompare(\"roll\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"rotate\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 's': { if (LocaleCompare(\"sample\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sampling-factor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"scale\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"scene\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"seed\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"segment\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"selective-blur\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"separate\",option+1) == 0) break; if (LocaleCompare(\"sepia-tone\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"set\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"shade\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"shadow\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sharpen\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"shave\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"shear\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sigmoidal-contrast\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"size\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sketch\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"smush\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; break; } if (LocaleCompare(\"solarize\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"sparse-color\",option+1) == 0) { ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickSparseColorOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedSparseColorMethod\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"splice\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"spread\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"statistic\",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); op=ParseCommandOption(MagickStatisticOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,\"UnrecognizedStatisticType\", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"stretch\",option+1) == 0) { ssize_t stretch; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,argv[i]); if (stretch < 0) ThrowMogrifyException(OptionError,\"UnrecognizedStyleType\", argv[i]); break; } if (LocaleCompare(\"strip\",option+1) == 0) break; if (LocaleCompare(\"stroke\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"strokewidth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"style\",option+1) == 0) { ssize_t style; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); style=ParseCommandOption(MagickStyleOptions,MagickFalse,argv[i]); if (style < 0) ThrowMogrifyException(OptionError,\"UnrecognizedStyleType\", argv[i]); break; } if (LocaleCompare(\"swap\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"swirl\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"synchronize\",option+1) == 0) break; ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 't': { if (LocaleCompare(\"taint\",option+1) == 0) break; if (LocaleCompare(\"texture\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"tile\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"tile-offset\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"tint\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"transform\",option+1) == 0) break; if (LocaleCompare(\"transpose\",option+1) == 0) break; if (LocaleCompare(\"transverse\",option+1) == 0) break; if (LocaleCompare(\"threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"thumbnail\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"transparent\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"transparent-color\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"treedepth\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"trim\",option+1) == 0) break; if (LocaleCompare(\"type\",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); type=ParseCommandOption(MagickTypeOptions,MagickFalse,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,\"UnrecognizedImageType\", argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'u': { if (LocaleCompare(\"undercolor\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"unique-colors\",option+1) == 0) break; if (LocaleCompare(\"units\",option+1) == 0) { ssize_t units; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); units=ParseCommandOption(MagickResolutionOptions,MagickFalse, argv[i]); if (units < 0) ThrowMogrifyException(OptionError,\"UnrecognizedUnitsType\", argv[i]); break; } if (LocaleCompare(\"unsharp\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'v': { if (LocaleCompare(\"verbose\",option+1) == 0) { image_info->verbose=(*option == '-') ? MagickTrue : MagickFalse; break; } if ((LocaleCompare(\"version\",option+1) == 0) || (LocaleCompare(\"-version\",option+1) == 0)) { ListMagickVersion(stdout); break; } if (LocaleCompare(\"view\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"vignette\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"virtual-pixel\",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); method=ParseCommandOption(MagickVirtualPixelOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError, \"UnrecognizedVirtualPixelMethod\",argv[i]); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case 'w': { if (LocaleCompare(\"wave\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"wavelet-denoise\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"weight\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } if (LocaleCompare(\"white-point\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"white-threshold\",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare(\"write\",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingArgument\",option); break; } ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } case '?': break; default: ThrowMogrifyException(OptionError,\"UnrecognizedOption\",option) } fire=(GetCommandOptionFlags(MagickCommandOptions,MagickFalse,option) & FireOptionFlag) == 0 ? MagickFalse : MagickTrue; if (fire != MagickFalse) FireImageStack(MagickFalse,MagickTrue,MagickTrue); } if (k != 0) ThrowMogrifyException(OptionError,\"UnbalancedParenthesis\",argv[i]); if (i != (ssize_t) argc) ThrowMogrifyException(OptionError,\"MissingAnImageFilename\",argv[i]); DestroyMogrify(); return(status != 0 ? MagickTrue : MagickFalse); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":274050,"input":"void CLASS parse_makernote (int base, int uptag) { unsigned offset=0, entries, tag, type, len, save, c; unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0}; uchar buf97[324], ci, cj, ck; short morder, sorder=order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif \/* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. *\/ if (!strncmp(make,\"Nokia\",5)) return; fread (buf, 1, 10, ifp); if (!strncmp (buf,\"KDK\" ,3) || \/* these aren't TIFF tables *\/ !strncmp (buf,\"VER\" ,3) || !strncmp (buf,\"IIII\",4) || !strncmp (buf,\"MMMM\",4)) return; if (!strncmp (buf,\"KC\" ,2) || \/* Konica KD-400Z, KD-510Z *\/ !strncmp (buf,\"MLY\" ,3)) { \/* Minolta DiMAGE G series *\/ order = 0x4d4d; while ((i=ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp (buf,\"Nikon\")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek (ifp, offset-8, SEEK_CUR); } else if (!strcmp (buf,\"OLYMPUS\") || !strcmp (buf,\"PENTAX \")) { base = ftell(ifp)-10; fseek (ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp (buf,\"SONY\",4) || !strcmp (buf,\"Panasonic\")) { goto nf; } else if (!strncmp (buf,\"FUJIFILM\",8)) { base = ftell(ifp)-10; nf: order = 0x4949; fseek (ifp, 2, SEEK_CUR); } else if (!strcmp (buf,\"OLYMP\") || !strcmp (buf,\"LEICA\") || !strcmp (buf,\"Ricoh\") || !strcmp (buf,\"EPSON\")) fseek (ifp, -2, SEEK_CUR); else if (!strcmp (buf,\"AOC\") || !strcmp (buf,\"QVC\")) fseek (ifp, -4, SEEK_CUR); else { fseek (ifp, -10, SEEK_CUR); if (!strncmp(make,\"SAMSUNG\",7)) base = ftell(ifp); } \/\/ adjust pos & base for Leica M8\/M9\/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, \"LEICA\", 5)) { if (!strncmp(model, \"M8\", 2) || !strncasecmp(model, \"Leica M8\", 8) || !strncasecmp(model, \"LEICA X\", 7)) { base = ftell(ifp)-8; } else if (!strncasecmp(model, \"LEICA M (Typ 240)\", 17)) { base = 0; } else if (!strncmp(model, \"M9\", 2) || !strncasecmp(model, \"Leica M9\", 8) || !strncasecmp(model, \"M Monochrom\", 11) || !strncasecmp(model, \"Leica M Monochrom\", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek (ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek (ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, \"LEICA T\", 7)) { base = ftell(ifp)-8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, \"LEICA SL\", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get (base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if(len > 8 && _pos+len > 2* fsize) continue; if (!strncmp(make, \"Canon\",5)) { if (tag == 0x000d && len < 256000) \/\/ camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) \/\/ Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; \/\/ M3 if (unique_id == 0x03840000) unique_id = 0x80000384; \/\/ M10 if (unique_id == 0x03940000) unique_id = 0x80000394; \/\/ M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, \"FUJI\", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18) if (i == 0) strncpy (imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial)-1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), \"%s %s\", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2); strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2); strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2); year = (yy[0]-'0')*10 + (yy[1]-'0'); if (year <70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, \"%2x\", &c); j += 2) ystr[j\/2] = c; ystr[ynum_len \/ 2 + 1] = 0; strcpy (model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf (tbuf,sizeof(tbuf), \"%s %s %d:%s:%s\", words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12, ystr, year, mm, dd); else snprintf (tbuf,sizeof(tbuf), \"%s %d:%s:%s %s\", ystr, year, mm, dd, words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), \"%s %s %d:%s:%s %s\", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } } } } else parseFujiMakernotes (tag, type); } else if (!strncasecmp(make, \"LEICA\", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, \"LEICA M\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, \"LEICA S\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, \"NIKON\",5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a*b)\/(float)c; } else if (tag == 0x0082) \/\/ lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) \/\/ lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) \/\/ lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) \/\/ lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12\/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops \/12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) \/\/ contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: \/\/ encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData>0) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) \/\/ contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, \"OLYMPUS\", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)\/2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid [3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(make, \"RICOH\", 5)) && !strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { char buffer[17]; int count=0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i=0; i<16; i++) { \/\/ sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, \"%02x\", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf (imgdata.shootinginfo.BodySerial, \"%8s\", buffer+8); buffer[8] = 0; sprintf (imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else { sprintf (imgdata.shootinginfo.BodySerial, \"%02x%02x%02x%02x\", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf (imgdata.shootinginfo.InternalBodySerial, \"%02x%02x%02x%02x\", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, \"RICOH\", 5) && strncmp(model, \"PENTAX\", 6)) { if ((tag == 0x0005) && !strncmp(model, \"GXR\", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf (imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, \"GXR\", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4()+20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch(imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(model, \"PENTAX\", 6) || (!strncmp(make, \"SAMSUNG\", 7) && dng_version)) && strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()\/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()\/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) \/ 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) \/ 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) \/\/ Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)\/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%d\", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) \/\/ Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, \" \"); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, \"SAMSUNG\", 7)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, \"NX mini\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() \/ 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, \"SONY\", 4) || !strncasecmp(make, \"Konica\", 6) || !strncasecmp(make, \"Minolta\", 7) || (!strncasecmp(make, \"Hasselblad\", 10) && (!strncasecmp(model, \"Stellar\", 7) || !strncasecmp(model, \"Lunar\", 5) || !strncasecmp(model, \"Lusso\", 5) || !strncasecmp(model, \"HV\",2)))) { ushort lid; if (tag == 0xb001) \/\/ Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && \/\/ CameraInfo strncasecmp(model, \"DSLR-A100\", 9) && strncasecmp(model, \"NEX-5C\", 6) && !strncasecmp(make, \"SONY\", 4) && ((len == 368) || \/\/ a700 (len == 5478) || \/\/ a850, a900 (len == 5506) || \/\/ a200, a300, a350 (len == 6118) || \/\/ a230, a290, a330, a380, a390 \/\/ a450, a500, a550, a560, a580 \/\/ a33, a35, a55 \/\/ NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, \"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\", 8) && memcmp(table_buf, \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\", 8)) { switch (len) { case 368: case 5478: \/\/ a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) \/ 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) \/ 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: \/\/ CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) \/ 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) \/ 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && \/\/ WBInfoA100, needs 0xb028 processing !strncasecmp(model, \"DSLR-A100\", 9)) { fseek(ifp,0x49dc,SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) \/\/ Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) \/\/ CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: \/\/ CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid\/8.0f-1.0f)\/2.0f); } break; case 1536: case 2048: \/\/ CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) \/\/ little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len <256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, \"MC-11\"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) \/\/ Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) \/ 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) \/ 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp,_pos,SEEK_SET); #endif if (tag == 2 && strstr(make,\"NIKON\") && !iso_speed) iso_speed = (get2(),get2()); if (tag == 37 && strstr(make,\"NIKON\") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc,1,1,ifp); iso_speed = int(100.0 * libraw_powf64(2.0f,float(cc)\/12.0-5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64(2.0, i\/32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i=(get2(),get2())) != 0x7fff && !aperture) aperture = libraw_powf64(2.0, i\/64.0); #endif if ((i=get2()) != 0xffff && !shutter) shutter = libraw_powf64(2.0, (short) i\/-32.0); wbi = (get2(),get2()); shot_order = (get2(),get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make,\"KONICA\",6)) { fseek (ifp, tag == 4 ? 140:160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets (model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make,\"Canon\",5)) fread (artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { for (c=i=2; (ushort) c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i+=4) < len-5) if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3) flip = \"065\"[c]-'0'; } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make,\"Olympus\",7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, \"E-410\", 5) || !strncasecmp(model, \"E-510\", 5))) { int i; for (i=0; i<64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i=64; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag-0x20400102; switch (nWB) { case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1 : CT = 3300; tWB = 0x100; break; case 2 : CT = 3600; tWB = 0x100; break; case 3 : CT = 3900; tWB = 0x100; break; case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5 : CT = 4300; tWB = 0x100; break; case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7 : CT = 4800; tWB = 0x100; break; case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag-0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i=0; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp,_pos2,SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make,\"NIKON\",5)) { fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek (ifp, 1248, SEEK_CUR); goto get2_256; } fread (buf, 1, 10, ifp); if (!strncmp(buf,\"NRW \",4)) { fseek (ifp, strcmp(buf+4,\"0100\") ? 46:1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread (model, 64, 1, ifp); if (strstr(make,\"PENTAX\")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,\"D50\"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, \"%d\", serial); #endif } if (tag == 0x29 && type == 1) { \/\/ Canon PowerShot G9 c = wbi < 18 ? \"012347800000005896\"[wbi]-'0' : 0; fseek (ifp, 8 + c*32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek (ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; switch (ver97) { case 100: fseek (ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek (ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek (ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek (ifp, 280, SEEK_CUR); fread (buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek (ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek (ifp, wbi*48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { \/\/ shutter count NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp); if ( (unsigned) (ver97-200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i=0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = \"66666>666;6A;:;55\"[ver97-200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2 (buf97 + (i & -2) + c*2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) \/\/ Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if(tag == 0xb001 && type == 3) \/\/ Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(),get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD \/\/ not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make,\"NIKON\") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black += i; } #endif if (tag == 0xe01) { \/* Nikon Capture Note *\/ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek (ifp, 22, SEEK_CUR); for (offset=22; offset+22 < len; offset += 22+i) { #ifdef LIBRAW_LIBRARY_BUILD if(loopc++>1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek (ifp, 14, SEEK_CUR); i = get4()-4; if (tag == 0x76a43207) flip = get2(); else fseek (ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek (ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 \/ 0x10000; cam_mul[2] = get2() * 382 * 1.173 \/ 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek (ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek (ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i=0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short) get2()) \/ 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short) get2()) \/ 256.0; } #else FORC3 cmatrix[i][c] = ((short) get2()) \/ 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() \/ 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() \/ 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() \/ 256.0; cam_mul[2] = get2() \/ 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek (ifp, get4()+base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD \/\/ IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp,_pos3,SEEK_SET); } if ( ((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make,\"Olympus\",7) ) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp,_pos3,SEEK_SET); } \/\/ IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,\"OLYMP\",5)) parse_thumb_note (base, 257, 258); if (tag == 0x2040) parse_makernote (base, 0x2040); if (tag == 0xb028) { fseek (ifp, get4()+base, SEEK_SET); parse_thumb_note (base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek (ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i+=18; i <= len; i+=10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if(!strncasecmp(make,\"Samsung\",7)) { if (tag == 0xa020) \/\/ get the full Samsung encryption key for (i=0; i<11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) \/\/ get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0]= imgdata.color.linear_max[1]= imgdata.color.linear_max[2]= imgdata.color.linear_max[3]= get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i=0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))\/256.0; #endif if (tag == 0xa031 && len == 9) \/\/ get and decode Samsung color matrix for (i=0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))\/256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { \/\/ Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":2684,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); if (image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError, \"MemoryAllocationFailed\"); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (Magick_png_color_equal(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (Magick_png_color_equal(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (Magick_png_color_equal(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) ThrowWriterException(ResourceLimitError, \"MemoryAllocationFailed\"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } \/* write any png-chunk-b profiles *\/ (void) Magick_png_write_chunk_from_profile(image,\"PNG-chunk-b\",logging); png_write_info(ping,ping_info); \/* write any PNG-chunk-m profiles *\/ (void) Magick_png_write_chunk_from_profile(image,\"PNG-chunk-m\",logging); ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif \/* write vpAg chunk (deprecated, replaced by caNv) *\/ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); \/* data length=8 *\/ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; \/* unit = pixels *\/ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { \/* Palette, Bilevel, or Opaque Monochrome *\/ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { \/* Undo pixel scaling *\/ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write any PNG-chunk-e profiles *\/ (void) Magick_png_write_chunk_from_profile(image,\"PNG-chunk-e\",logging); \/* write exIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"True","vulnerability_types":["NULL Pointer Dereference"],"explanation":"The WriteOnePNGImage function in coders\/png.c in ImageMagick through 6.9.9-0 and 7.x through 7.0.6-1 allows remote attackers to cause a denial of service (NULL pointer dereference) via a crafted file.","severity_level":"Medium","cwe":"CWE-476","cve":"CVE-2017-11522"}} -{"idx":194899,"input":"yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else \/* ! YYPARSE_PARAM *\/ #if (defined __STDC__ || defined __C99__FUNC__ \\ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { int yystate; \/* Number of tokens to shift before error messages enabled. *\/ int yyerrstatus; \/* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. *\/ \/* The state stack. *\/ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; \/* The semantic value stack. *\/ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; \/* Lookahead token as an internal (translated) token number. *\/ int yytoken; \/* The variables used to return semantic value and location from the action routines. *\/ YYSTYPE yyval; #if YYERROR_VERBOSE \/* Buffer for error messages, and its allocated size. *\/ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) \/* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. *\/ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, \"Starting parse\\n\")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; \/* Cause a token to be read. *\/ \/* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. *\/ yyssp = yyss; yyvsp = yyvs; goto yysetstate; \/*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*\/ yynewstate: \/* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. *\/ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { \/* Get the current used size of the three stacks, in elements. *\/ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { \/* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. *\/ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; \/* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. *\/ yyoverflow (YY_(\"memory exhausted\"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else \/* no yyoverflow *\/ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else \/* Extend the stack our own way. *\/ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif \/* no yyoverflow *\/ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, \"Stack size increased to %lu\\n\", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, \"Entering state %d\\n\", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; \/*-----------. | yybackup. | `-----------*\/ yybackup: \/* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. *\/ \/* First try to decide what to do without reference to lookahead token. *\/ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; \/* Not known => get a lookahead token if don't already have one. *\/ \/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. *\/ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, \"Reading a token: \")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, \"Now at end of input.\\n\")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT (\"Next token is\", yytoken, &yylval, &yylloc); } \/* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. *\/ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } \/* Count tokens shifted since error; after three, turn off error status. *\/ if (yyerrstatus) yyerrstatus--; \/* Shift the lookahead token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yytoken, &yylval, &yylloc); \/* Discard the shifted token. *\/ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; \/*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*\/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; \/*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*\/ yyreduce: \/* yyn is the number of a rule to reduce with. *\/ yylen = yyr2[yyn]; \/* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. *\/ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: \/* Line 1455 of yacc.c *\/ #line 320 \"ntp_parser.y\" { \/* I will need to incorporate much more fine grained * error messages. The following should suffice for * the time being. *\/ msyslog(LOG_ERR, \"syntax error in %s line %d, column %d\", ip_file->fname, ip_file->err_line_no, ip_file->err_col_no); } break; case 19: \/* Line 1455 of yacc.c *\/ #line 354 \"ntp_parser.y\" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (3)].Integer), (yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue)); if (my_node) enqueue(cfgt.peers, my_node); } break; case 20: \/* Line 1455 of yacc.c *\/ #line 360 \"ntp_parser.y\" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node), NULL); if (my_node) enqueue(cfgt.peers, my_node); } break; case 27: \/* Line 1455 of yacc.c *\/ #line 377 \"ntp_parser.y\" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET); } break; case 28: \/* Line 1455 of yacc.c *\/ #line 378 \"ntp_parser.y\" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET6); } break; case 29: \/* Line 1455 of yacc.c *\/ #line 382 \"ntp_parser.y\" { (yyval.Address_node) = create_address_node((yyvsp[(1) - (1)].String), 0); } break; case 30: \/* Line 1455 of yacc.c *\/ #line 386 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 31: \/* Line 1455 of yacc.c *\/ #line 387 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 32: \/* Line 1455 of yacc.c *\/ #line 391 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 33: \/* Line 1455 of yacc.c *\/ #line 392 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 34: \/* Line 1455 of yacc.c *\/ #line 393 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 35: \/* Line 1455 of yacc.c *\/ #line 394 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 36: \/* Line 1455 of yacc.c *\/ #line 395 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 37: \/* Line 1455 of yacc.c *\/ #line 396 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 38: \/* Line 1455 of yacc.c *\/ #line 397 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 39: \/* Line 1455 of yacc.c *\/ #line 398 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 40: \/* Line 1455 of yacc.c *\/ #line 399 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 41: \/* Line 1455 of yacc.c *\/ #line 400 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 42: \/* Line 1455 of yacc.c *\/ #line 401 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 43: \/* Line 1455 of yacc.c *\/ #line 402 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 44: \/* Line 1455 of yacc.c *\/ #line 403 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 45: \/* Line 1455 of yacc.c *\/ #line 404 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 46: \/* Line 1455 of yacc.c *\/ #line 405 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 47: \/* Line 1455 of yacc.c *\/ #line 415 \"ntp_parser.y\" { struct unpeer_node *my_node = create_unpeer_node((yyvsp[(2) - (2)].Address_node)); if (my_node) enqueue(cfgt.unpeers, my_node); } break; case 50: \/* Line 1455 of yacc.c *\/ #line 434 \"ntp_parser.y\" { cfgt.broadcastclient = 1; } break; case 51: \/* Line 1455 of yacc.c *\/ #line 436 \"ntp_parser.y\" { append_queue(cfgt.manycastserver, (yyvsp[(2) - (2)].Queue)); } break; case 52: \/* Line 1455 of yacc.c *\/ #line 438 \"ntp_parser.y\" { append_queue(cfgt.multicastclient, (yyvsp[(2) - (2)].Queue)); } break; case 53: \/* Line 1455 of yacc.c *\/ #line 449 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 54: \/* Line 1455 of yacc.c *\/ #line 451 \"ntp_parser.y\" { cfgt.auth.control_key = (yyvsp[(2) - (2)].Integer); } break; case 55: \/* Line 1455 of yacc.c *\/ #line 453 \"ntp_parser.y\" { cfgt.auth.cryptosw++; append_queue(cfgt.auth.crypto_cmd_list, (yyvsp[(2) - (2)].Queue)); } break; case 56: \/* Line 1455 of yacc.c *\/ #line 458 \"ntp_parser.y\" { cfgt.auth.keys = (yyvsp[(2) - (2)].String); } break; case 57: \/* Line 1455 of yacc.c *\/ #line 460 \"ntp_parser.y\" { cfgt.auth.keysdir = (yyvsp[(2) - (2)].String); } break; case 58: \/* Line 1455 of yacc.c *\/ #line 462 \"ntp_parser.y\" { cfgt.auth.request_key = (yyvsp[(2) - (2)].Integer); } break; case 59: \/* Line 1455 of yacc.c *\/ #line 464 \"ntp_parser.y\" { cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); } break; case 60: \/* Line 1455 of yacc.c *\/ #line 466 \"ntp_parser.y\" { cfgt.auth.trusted_key_list = (yyvsp[(2) - (2)].Queue); } break; case 61: \/* Line 1455 of yacc.c *\/ #line 468 \"ntp_parser.y\" { cfgt.auth.ntp_signd_socket = (yyvsp[(2) - (2)].String); } break; case 63: \/* Line 1455 of yacc.c *\/ #line 474 \"ntp_parser.y\" { (yyval.Queue) = create_queue(); } break; case 64: \/* Line 1455 of yacc.c *\/ #line 479 \"ntp_parser.y\" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 65: \/* Line 1455 of yacc.c *\/ #line 486 \"ntp_parser.y\" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 66: \/* Line 1455 of yacc.c *\/ #line 496 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 67: \/* Line 1455 of yacc.c *\/ #line 498 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 68: \/* Line 1455 of yacc.c *\/ #line 500 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 69: \/* Line 1455 of yacc.c *\/ #line 502 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 70: \/* Line 1455 of yacc.c *\/ #line 504 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 71: \/* Line 1455 of yacc.c *\/ #line 506 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 72: \/* Line 1455 of yacc.c *\/ #line 508 \"ntp_parser.y\" { (yyval.Attr_val) = NULL; cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); msyslog(LOG_WARNING, \"'crypto revoke %d' is deprecated, \" \"please use 'revoke %d' instead.\", cfgt.auth.revoke, cfgt.auth.revoke); } break; case 73: \/* Line 1455 of yacc.c *\/ #line 525 \"ntp_parser.y\" { append_queue(cfgt.orphan_cmds,(yyvsp[(2) - (2)].Queue)); } break; case 74: \/* Line 1455 of yacc.c *\/ #line 529 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 75: \/* Line 1455 of yacc.c *\/ #line 530 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 76: \/* Line 1455 of yacc.c *\/ #line 535 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 77: \/* Line 1455 of yacc.c *\/ #line 537 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 78: \/* Line 1455 of yacc.c *\/ #line 539 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 79: \/* Line 1455 of yacc.c *\/ #line 541 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 80: \/* Line 1455 of yacc.c *\/ #line 543 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 81: \/* Line 1455 of yacc.c *\/ #line 545 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 82: \/* Line 1455 of yacc.c *\/ #line 547 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 83: \/* Line 1455 of yacc.c *\/ #line 549 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 84: \/* Line 1455 of yacc.c *\/ #line 551 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 85: \/* Line 1455 of yacc.c *\/ #line 553 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 86: \/* Line 1455 of yacc.c *\/ #line 555 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 87: \/* Line 1455 of yacc.c *\/ #line 565 \"ntp_parser.y\" { append_queue(cfgt.stats_list, (yyvsp[(2) - (2)].Queue)); } break; case 88: \/* Line 1455 of yacc.c *\/ #line 567 \"ntp_parser.y\" { if (input_from_file) cfgt.stats_dir = (yyvsp[(2) - (2)].String); else { free((yyvsp[(2) - (2)].String)); yyerror(\"statsdir remote configuration ignored\"); } } break; case 89: \/* Line 1455 of yacc.c *\/ #line 576 \"ntp_parser.y\" { enqueue(cfgt.filegen_opts, create_filegen_node((yyvsp[(2) - (3)].Integer), (yyvsp[(3) - (3)].Queue))); } break; case 90: \/* Line 1455 of yacc.c *\/ #line 583 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 91: \/* Line 1455 of yacc.c *\/ #line 584 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 100: \/* Line 1455 of yacc.c *\/ #line 600 \"ntp_parser.y\" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 101: \/* Line 1455 of yacc.c *\/ #line 607 \"ntp_parser.y\" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 102: \/* Line 1455 of yacc.c *\/ #line 617 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); else { (yyval.Attr_val) = NULL; free((yyvsp[(2) - (2)].String)); yyerror(\"filegen file remote configuration ignored\"); } } break; case 103: \/* Line 1455 of yacc.c *\/ #line 627 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); else { (yyval.Attr_val) = NULL; yyerror(\"filegen type remote configuration ignored\"); } } break; case 104: \/* Line 1455 of yacc.c *\/ #line 636 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror(\"filegen link remote configuration ignored\"); } } break; case 105: \/* Line 1455 of yacc.c *\/ #line 645 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror(\"filegen nolink remote configuration ignored\"); } } break; case 106: \/* Line 1455 of yacc.c *\/ #line 653 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 107: \/* Line 1455 of yacc.c *\/ #line 654 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 115: \/* Line 1455 of yacc.c *\/ #line 674 \"ntp_parser.y\" { append_queue(cfgt.discard_opts, (yyvsp[(2) - (2)].Queue)); } break; case 116: \/* Line 1455 of yacc.c *\/ #line 678 \"ntp_parser.y\" { append_queue(cfgt.mru_opts, (yyvsp[(2) - (2)].Queue)); } break; case 117: \/* Line 1455 of yacc.c *\/ #line 682 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (3)].Address_node), NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 118: \/* Line 1455 of yacc.c *\/ #line 687 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (5)].Address_node), (yyvsp[(4) - (5)].Address_node), (yyvsp[(5) - (5)].Queue), ip_file->line_no)); } break; case 119: \/* Line 1455 of yacc.c *\/ #line 692 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node(NULL, NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 120: \/* Line 1455 of yacc.c *\/ #line 697 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup(\"0.0.0.0\"), AF_INET), create_address_node( estrdup(\"0.0.0.0\"), AF_INET), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 121: \/* Line 1455 of yacc.c *\/ #line 710 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup(\"::\"), AF_INET6), create_address_node( estrdup(\"::\"), AF_INET6), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 122: \/* Line 1455 of yacc.c *\/ #line 723 \"ntp_parser.y\" { enqueue(cfgt.restrict_opts, create_restrict_node( NULL, NULL, enqueue((yyvsp[(3) - (3)].Queue), create_ival((yyvsp[(2) - (3)].Integer))), ip_file->line_no)); } break; case 123: \/* Line 1455 of yacc.c *\/ #line 734 \"ntp_parser.y\" { (yyval.Queue) = create_queue(); } break; case 124: \/* Line 1455 of yacc.c *\/ #line 736 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 139: \/* Line 1455 of yacc.c *\/ #line 758 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 140: \/* Line 1455 of yacc.c *\/ #line 760 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 141: \/* Line 1455 of yacc.c *\/ #line 764 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 142: \/* Line 1455 of yacc.c *\/ #line 765 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 143: \/* Line 1455 of yacc.c *\/ #line 766 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 144: \/* Line 1455 of yacc.c *\/ #line 771 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 145: \/* Line 1455 of yacc.c *\/ #line 773 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 146: \/* Line 1455 of yacc.c *\/ #line 777 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 147: \/* Line 1455 of yacc.c *\/ #line 778 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 148: \/* Line 1455 of yacc.c *\/ #line 779 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 149: \/* Line 1455 of yacc.c *\/ #line 780 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 150: \/* Line 1455 of yacc.c *\/ #line 781 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 151: \/* Line 1455 of yacc.c *\/ #line 782 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 152: \/* Line 1455 of yacc.c *\/ #line 783 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 153: \/* Line 1455 of yacc.c *\/ #line 784 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 154: \/* Line 1455 of yacc.c *\/ #line 793 \"ntp_parser.y\" { enqueue(cfgt.fudge, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 155: \/* Line 1455 of yacc.c *\/ #line 798 \"ntp_parser.y\" { enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 156: \/* Line 1455 of yacc.c *\/ #line 800 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 157: \/* Line 1455 of yacc.c *\/ #line 804 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 158: \/* Line 1455 of yacc.c *\/ #line 805 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 159: \/* Line 1455 of yacc.c *\/ #line 806 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 160: \/* Line 1455 of yacc.c *\/ #line 807 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 161: \/* Line 1455 of yacc.c *\/ #line 808 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 162: \/* Line 1455 of yacc.c *\/ #line 809 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 163: \/* Line 1455 of yacc.c *\/ #line 810 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 164: \/* Line 1455 of yacc.c *\/ #line 811 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 165: \/* Line 1455 of yacc.c *\/ #line 820 \"ntp_parser.y\" { append_queue(cfgt.enable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 166: \/* Line 1455 of yacc.c *\/ #line 822 \"ntp_parser.y\" { append_queue(cfgt.disable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 167: \/* Line 1455 of yacc.c *\/ #line 827 \"ntp_parser.y\" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 168: \/* Line 1455 of yacc.c *\/ #line 834 \"ntp_parser.y\" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 169: \/* Line 1455 of yacc.c *\/ #line 843 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 170: \/* Line 1455 of yacc.c *\/ #line 844 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 171: \/* Line 1455 of yacc.c *\/ #line 845 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 172: \/* Line 1455 of yacc.c *\/ #line 846 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 173: \/* Line 1455 of yacc.c *\/ #line 847 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 174: \/* Line 1455 of yacc.c *\/ #line 848 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 175: \/* Line 1455 of yacc.c *\/ #line 850 \"ntp_parser.y\" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror(\"enable\/disable stats remote configuration ignored\"); } } break; case 176: \/* Line 1455 of yacc.c *\/ #line 865 \"ntp_parser.y\" { append_queue(cfgt.tinker, (yyvsp[(2) - (2)].Queue)); } break; case 177: \/* Line 1455 of yacc.c *\/ #line 869 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 178: \/* Line 1455 of yacc.c *\/ #line 870 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 179: \/* Line 1455 of yacc.c *\/ #line 874 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 180: \/* Line 1455 of yacc.c *\/ #line 875 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 181: \/* Line 1455 of yacc.c *\/ #line 876 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 182: \/* Line 1455 of yacc.c *\/ #line 877 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 183: \/* Line 1455 of yacc.c *\/ #line 878 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 184: \/* Line 1455 of yacc.c *\/ #line 879 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 185: \/* Line 1455 of yacc.c *\/ #line 880 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 187: \/* Line 1455 of yacc.c *\/ #line 891 \"ntp_parser.y\" { if (curr_include_level >= MAXINCLUDELEVEL) { fprintf(stderr, \"getconfig: Maximum include file level exceeded.\\n\"); msyslog(LOG_ERR, \"getconfig: Maximum include file level exceeded.\"); } else { fp[curr_include_level + 1] = F_OPEN(FindConfig((yyvsp[(2) - (3)].String)), \"r\"); if (fp[curr_include_level + 1] == NULL) { fprintf(stderr, \"getconfig: Couldn't open <%s>\\n\", FindConfig((yyvsp[(2) - (3)].String))); msyslog(LOG_ERR, \"getconfig: Couldn't open <%s>\", FindConfig((yyvsp[(2) - (3)].String))); } else ip_file = fp[++curr_include_level]; } } break; case 188: \/* Line 1455 of yacc.c *\/ #line 907 \"ntp_parser.y\" { while (curr_include_level != -1) FCLOSE(fp[curr_include_level--]); } break; case 189: \/* Line 1455 of yacc.c *\/ #line 913 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 190: \/* Line 1455 of yacc.c *\/ #line 915 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 191: \/* Line 1455 of yacc.c *\/ #line 917 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 192: \/* Line 1455 of yacc.c *\/ #line 919 \"ntp_parser.y\" { \/* Null action, possibly all null parms *\/ } break; case 193: \/* Line 1455 of yacc.c *\/ #line 921 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 194: \/* Line 1455 of yacc.c *\/ #line 924 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 195: \/* Line 1455 of yacc.c *\/ #line 926 \"ntp_parser.y\" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror(\"logfile remote configuration ignored\"); } } break; case 196: \/* Line 1455 of yacc.c *\/ #line 937 \"ntp_parser.y\" { append_queue(cfgt.logconfig, (yyvsp[(2) - (2)].Queue)); } break; case 197: \/* Line 1455 of yacc.c *\/ #line 939 \"ntp_parser.y\" { append_queue(cfgt.phone, (yyvsp[(2) - (2)].Queue)); } break; case 198: \/* Line 1455 of yacc.c *\/ #line 941 \"ntp_parser.y\" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror(\"saveconfigdir remote configuration ignored\"); } } break; case 199: \/* Line 1455 of yacc.c *\/ #line 951 \"ntp_parser.y\" { enqueue(cfgt.setvar, (yyvsp[(2) - (2)].Set_var)); } break; case 200: \/* Line 1455 of yacc.c *\/ #line 953 \"ntp_parser.y\" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (2)].Address_node), NULL)); } break; case 201: \/* Line 1455 of yacc.c *\/ #line 955 \"ntp_parser.y\" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 202: \/* Line 1455 of yacc.c *\/ #line 957 \"ntp_parser.y\" { append_queue(cfgt.ttl, (yyvsp[(2) - (2)].Queue)); } break; case 203: \/* Line 1455 of yacc.c *\/ #line 959 \"ntp_parser.y\" { enqueue(cfgt.qos, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 204: \/* Line 1455 of yacc.c *\/ #line 964 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (1)].String))); } break; case 205: \/* Line 1455 of yacc.c *\/ #line 966 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_dval(T_WanderThreshold, (yyvsp[(2) - (2)].Double))); enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (2)].String))); } break; case 206: \/* Line 1455 of yacc.c *\/ #line 969 \"ntp_parser.y\" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, \"\\0\")); } break; case 207: \/* Line 1455 of yacc.c *\/ #line 974 \"ntp_parser.y\" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (4)].String), (yyvsp[(3) - (4)].String), (yyvsp[(4) - (4)].Integer)); } break; case 208: \/* Line 1455 of yacc.c *\/ #line 976 \"ntp_parser.y\" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (3)].String), (yyvsp[(3) - (3)].String), 0); } break; case 209: \/* Line 1455 of yacc.c *\/ #line 981 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 210: \/* Line 1455 of yacc.c *\/ #line 982 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 211: \/* Line 1455 of yacc.c *\/ #line 986 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 212: \/* Line 1455 of yacc.c *\/ #line 987 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_pval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node)); } break; case 213: \/* Line 1455 of yacc.c *\/ #line 991 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 214: \/* Line 1455 of yacc.c *\/ #line 992 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 215: \/* Line 1455 of yacc.c *\/ #line 997 \"ntp_parser.y\" { char prefix; char * type; switch ((yyvsp[(1) - (1)].String)[0]) { case '+': case '-': case '=': prefix = (yyvsp[(1) - (1)].String)[0]; type = (yyvsp[(1) - (1)].String) + 1; break; default: prefix = '='; type = (yyvsp[(1) - (1)].String); } (yyval.Attr_val) = create_attr_sval(prefix, estrdup(type)); YYFREE((yyvsp[(1) - (1)].String)); } break; case 216: \/* Line 1455 of yacc.c *\/ #line 1022 \"ntp_parser.y\" { enqueue(cfgt.nic_rules, create_nic_rule_node((yyvsp[(3) - (3)].Integer), NULL, (yyvsp[(2) - (3)].Integer))); } break; case 217: \/* Line 1455 of yacc.c *\/ #line 1027 \"ntp_parser.y\" { enqueue(cfgt.nic_rules, create_nic_rule_node(0, (yyvsp[(3) - (3)].String), (yyvsp[(2) - (3)].Integer))); } break; case 227: \/* Line 1455 of yacc.c *\/ #line 1058 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 228: \/* Line 1455 of yacc.c *\/ #line 1059 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 229: \/* Line 1455 of yacc.c *\/ #line 1064 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 230: \/* Line 1455 of yacc.c *\/ #line 1066 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 231: \/* Line 1455 of yacc.c *\/ #line 1071 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_ival('i', (yyvsp[(1) - (1)].Integer)); } break; case 233: \/* Line 1455 of yacc.c *\/ #line 1077 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_shorts('-', (yyvsp[(2) - (5)].Integer), (yyvsp[(4) - (5)].Integer)); } break; case 234: \/* Line 1455 of yacc.c *\/ #line 1081 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_pval((yyvsp[(2) - (2)].String))); } break; case 235: \/* Line 1455 of yacc.c *\/ #line 1082 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue(create_pval((yyvsp[(1) - (1)].String))); } break; case 236: \/* Line 1455 of yacc.c *\/ #line 1086 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Address_node)); } break; case 237: \/* Line 1455 of yacc.c *\/ #line 1087 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Address_node)); } break; case 238: \/* Line 1455 of yacc.c *\/ #line 1092 \"ntp_parser.y\" { if ((yyvsp[(1) - (1)].Integer) != 0 && (yyvsp[(1) - (1)].Integer) != 1) { yyerror(\"Integer value is not boolean (0 or 1). Assuming 1\"); (yyval.Integer) = 1; } else (yyval.Integer) = (yyvsp[(1) - (1)].Integer); } break; case 239: \/* Line 1455 of yacc.c *\/ #line 1100 \"ntp_parser.y\" { (yyval.Integer) = 1; } break; case 240: \/* Line 1455 of yacc.c *\/ #line 1101 \"ntp_parser.y\" { (yyval.Integer) = 0; } break; case 241: \/* Line 1455 of yacc.c *\/ #line 1105 \"ntp_parser.y\" { (yyval.Double) = (double)(yyvsp[(1) - (1)].Integer); } break; case 243: \/* Line 1455 of yacc.c *\/ #line 1116 \"ntp_parser.y\" { cfgt.sim_details = create_sim_node((yyvsp[(3) - (5)].Queue), (yyvsp[(4) - (5)].Queue)); \/* Reset the old_config_style variable *\/ old_config_style = 1; } break; case 244: \/* Line 1455 of yacc.c *\/ #line 1130 \"ntp_parser.y\" { old_config_style = 0; } break; case 245: \/* Line 1455 of yacc.c *\/ #line 1134 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 246: \/* Line 1455 of yacc.c *\/ #line 1135 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 247: \/* Line 1455 of yacc.c *\/ #line 1139 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 248: \/* Line 1455 of yacc.c *\/ #line 1140 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 249: \/* Line 1455 of yacc.c *\/ #line 1144 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_server)); } break; case 250: \/* Line 1455 of yacc.c *\/ #line 1145 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_server)); } break; case 251: \/* Line 1455 of yacc.c *\/ #line 1150 \"ntp_parser.y\" { (yyval.Sim_server) = create_sim_server((yyvsp[(1) - (5)].Address_node), (yyvsp[(3) - (5)].Double), (yyvsp[(4) - (5)].Queue)); } break; case 252: \/* Line 1455 of yacc.c *\/ #line 1154 \"ntp_parser.y\" { (yyval.Double) = (yyvsp[(3) - (4)].Double); } break; case 253: \/* Line 1455 of yacc.c *\/ #line 1158 \"ntp_parser.y\" { (yyval.Address_node) = (yyvsp[(3) - (3)].Address_node); } break; case 254: \/* Line 1455 of yacc.c *\/ #line 1162 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_script)); } break; case 255: \/* Line 1455 of yacc.c *\/ #line 1163 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_script)); } break; case 256: \/* Line 1455 of yacc.c *\/ #line 1168 \"ntp_parser.y\" { (yyval.Sim_script) = create_sim_script_info((yyvsp[(3) - (6)].Double), (yyvsp[(5) - (6)].Queue)); } break; case 257: \/* Line 1455 of yacc.c *\/ #line 1172 \"ntp_parser.y\" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 258: \/* Line 1455 of yacc.c *\/ #line 1173 \"ntp_parser.y\" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 259: \/* Line 1455 of yacc.c *\/ #line 1178 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 260: \/* Line 1455 of yacc.c *\/ #line 1180 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 261: \/* Line 1455 of yacc.c *\/ #line 1182 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 262: \/* Line 1455 of yacc.c *\/ #line 1184 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 263: \/* Line 1455 of yacc.c *\/ #line 1186 \"ntp_parser.y\" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; \/* Line 1455 of yacc.c *\/ #line 3836 \"ntp_parser.c\" default: break; } YY_SYMBOL_PRINT (\"-> $$ =\", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; \/* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. *\/ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; \/*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*\/ yyerrlab: \/* If not already recovering from an error, report this error. *\/ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_(\"syntax error\")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_(\"syntax error\")); if (yysize != 0) goto yyexhaustedlab; } } #endif } if (yyerrstatus == 3) { \/* If just tried and failed to reuse lookahead token after an error, discard it. *\/ if (yychar <= YYEOF) { \/* Return failure if at end of input. *\/ if (yychar == YYEOF) YYABORT; } else { yydestruct (\"Error: discarding\", yytoken, &yylval); yychar = YYEMPTY; } } \/* Else will try to reuse lookahead token after shifting the error token. *\/ goto yyerrlab1; \/*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*\/ yyerrorlab: \/* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. *\/ if (\/*CONSTCOND*\/ 0) goto yyerrorlab; \/* Do not reclaim the symbols of the rule which action triggered this YYERROR. *\/ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; \/*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*\/ yyerrlab1: yyerrstatus = 3; \/* Each real token shifted decrements this. *\/ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } \/* Pop the current state because it cannot handle the error token. *\/ if (yyssp == yyss) YYABORT; yydestruct (\"Error: popping\", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; \/* Shift the error token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; \/*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*\/ yyacceptlab: yyresult = 0; goto yyreturn; \/*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*\/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE \/*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*\/ yyexhaustedlab: yyerror (YY_(\"memory exhausted\")); yyresult = 2; \/* Fall through. *\/ #endif yyreturn: if (yychar != YYEMPTY) yydestruct (\"Cleanup: discarding lookahead\", yytoken, &yylval); \/* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. *\/ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct (\"Cleanup: popping\", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif \/* Make sure YYID is used. *\/ return YYID (yyresult); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":194753,"input":"PHP_METHOD(Phar, webPhar) { zval *mimeoverride = NULL, *rewrite = NULL; char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL; int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0; char *fname, *path_info, *mime_type = NULL, *entry, *pt; const char *basename; int fname_len, entry_len, code, index_php_len = 0, not_cgi; phar_archive_data *phar = NULL; phar_entry_info *info = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s!s!saz\", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } return; } \/* retrieve requested file within phar *\/ if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, \"GET\") || !strcmp(SG(request_info).request_method, \"POST\")))) { return; } #ifdef PHP_WIN32 fname = estrndup(fname, fname_len); phar_unixify_path_separators(fname, fname_len); #endif basename = zend_memrchr(fname, '\/', fname_len); if (!basename) { basename = fname; } else { ++basename; } if ((strlen(sapi_module.name) == sizeof(\"cgi-fcgi\")-1 && !strncmp(sapi_module.name, \"cgi-fcgi\", sizeof(\"cgi-fcgi\")-1)) || (strlen(sapi_module.name) == sizeof(\"fpm-fcgi\")-1 && !strncmp(sapi_module.name, \"fpm-fcgi\", sizeof(\"fpm-fcgi\")-1)) || (strlen(sapi_module.name) == sizeof(\"cgi\")-1 && !strncmp(sapi_module.name, \"cgi\", sizeof(\"cgi\")-1))) { if (PG(http_globals)[TRACK_VARS_SERVER]) { HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]); zval **z_script_name, **z_path_info; if (SUCCESS != zend_hash_find(_server, \"SCRIPT_NAME\", sizeof(\"SCRIPT_NAME\"), (void**)&z_script_name) || IS_STRING != Z_TYPE_PP(z_script_name) || !strstr(Z_STRVAL_PP(z_script_name), basename)) { return; } if (SUCCESS == zend_hash_find(_server, \"PATH_INFO\", sizeof(\"PATH_INFO\"), (void**)&z_path_info) && IS_STRING == Z_TYPE_PP(z_path_info)) { entry_len = Z_STRLEN_PP(z_path_info); entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len); path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1); memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1); free_pathinfo = 1; } else { entry_len = 0; entry = estrndup(\"\", 0); path_info = Z_STRVAL_PP(z_script_name); } pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); } else { char *testit; testit = sapi_getenv(\"SCRIPT_NAME\", sizeof(\"SCRIPT_NAME\")-1 TSRMLS_CC); if (!(pt = strstr(testit, basename))) { efree(testit); return; } path_info = sapi_getenv(\"PATH_INFO\", sizeof(\"PATH_INFO\")-1 TSRMLS_CC); if (path_info) { entry = path_info; entry_len = strlen(entry); spprintf(&path_info, 0, \"%s%s\", testit, path_info); free_pathinfo = 1; } else { path_info = testit; free_pathinfo = 1; entry = estrndup(\"\", 0); entry_len = 0; } pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname))); } not_cgi = 0; } else { path_info = SG(request_info).request_uri; if (!(pt = strstr(path_info, basename))) { \/* this can happen with rewrite rules - and we have no idea what to do then, so return *\/ return; } entry_len = strlen(path_info); entry_len -= (pt - path_info) + (fname_len - (basename - fname)); entry = estrndup(pt + (fname_len - (basename - fname)), entry_len); pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname))); not_cgi = 1; } if (rewrite) { zend_fcall_info fci; zend_fcall_info_cache fcc; zval *params, *retval_ptr, **zp[1]; MAKE_STD_ZVAL(params); ZVAL_STRINGL(params, entry, entry_len, 1); zp[0] = ¶ms; #if PHP_VERSION_ID < 50300 if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) { #else if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) { #endif zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar error: invalid rewrite callback\"); if (free_pathinfo) { efree(path_info); } return; } fci.param_count = 1; fci.params = zp; #if PHP_VERSION_ID < 50300 ++(params->refcount); #else Z_ADDREF_P(params); #endif fci.retval_ptr_ptr = &retval_ptr; if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) { if (!EG(exception)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar error: failed to call rewrite callback\"); } if (free_pathinfo) { efree(path_info); } return; } if (!fci.retval_ptr_ptr || !retval_ptr) { if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar error: rewrite callback must return a string or false\"); return; } switch (Z_TYPE_P(retval_ptr)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(retval_ptr TSRMLS_CC); \/* break intentionally omitted *\/ #endif case IS_STRING: efree(entry); if (fci.retval_ptr_ptr != &retval_ptr) { entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr)); entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr); } else { entry = Z_STRVAL_P(retval_ptr); entry_len = Z_STRLEN_P(retval_ptr); } break; case IS_BOOL: phar_do_403(entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); return; default: efree(retval_ptr); if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar error: rewrite callback must return a string or false\"); return; } } if (entry_len) { phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC); } if (!entry_len || (entry_len == 1 && entry[0] == '\/')) { efree(entry); \/* direct request *\/ if (index_php_len) { entry = index_php; entry_len = index_php_len; if (entry[0] != '\/') { spprintf(&entry, 0, \"\/%s\", index_php); ++entry_len; } } else { \/* assume \"index.php\" is starting point *\/ entry = estrndup(\"\/index.php\", sizeof(\"\/index.php\")); entry_len = sizeof(\"\/index.php\")-1; } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); } else { char *tmp = NULL, sa = '\\0'; sapi_header_line ctr = {0}; ctr.response_code = 301; ctr.line_len = sizeof(\"HTTP\/1.1 301 Moved Permanently\")-1; ctr.line = \"HTTP\/1.1 301 Moved Permanently\"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); if (not_cgi) { tmp = strstr(path_info, basename) + fname_len; sa = *tmp; *tmp = '\\0'; } ctr.response_code = 0; if (path_info[strlen(path_info)-1] == '\/') { ctr.line_len = spprintf(&(ctr.line), 4096, \"Location: %s%s\", path_info, entry + 1); } else { ctr.line_len = spprintf(&(ctr.line), 4096, \"Location: %s%s\", path_info, entry); } if (not_cgi) { *tmp = sa; } if (free_pathinfo) { efree(path_info); } sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); sapi_send_headers(TSRMLS_C); efree(ctr.line); zend_bailout(); } } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); #ifdef PHP_WIN32 efree(fname); #endif zend_bailout(); } if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) { const char *ext = zend_memrchr(entry, '.', entry_len); zval **val; if (ext) { ++ext; if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) { switch (Z_TYPE_PP(val)) { case IS_LONG: if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) { mime_type = \"\"; code = Z_LVAL_PP(val); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed\"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } break; case IS_STRING: mime_type = Z_STRVAL_PP(val); code = PHAR_MIME_OTHER; break; default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed\"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } } } } if (!mime_type) { code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC); } ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC); } \/* }}} *\/ \/* {{{ proto void Phar::mungServer(array munglist) * Defines a list of up to 4 $_SERVER variables that should be modified for execution * to mask the presence of the phar archive. This should be used in conjunction with * Phar::webPhar(), and has no effect otherwise * SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME *\/ PHP_METHOD(Phar, mungServer) { zval *mungvalues; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"a\", &mungvalues) == FAILURE) { return; } if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME\"); return; } if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME\"); return; } phar_request_initialize(TSRMLS_C); for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) { zval **data = NULL; if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"unable to retrieve array value in Phar::mungServer()\"); return; } if (Z_TYPE_PP(data) != IS_STRING) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME\"); return; } if (Z_STRLEN_PP(data) == sizeof(\"PHP_SELF\")-1 && !strncmp(Z_STRVAL_PP(data), \"PHP_SELF\", sizeof(\"PHP_SELF\")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF; } if (Z_STRLEN_PP(data) == sizeof(\"REQUEST_URI\")-1) { if (!strncmp(Z_STRVAL_PP(data), \"REQUEST_URI\", sizeof(\"REQUEST_URI\")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI; } if (!strncmp(Z_STRVAL_PP(data), \"SCRIPT_NAME\", sizeof(\"SCRIPT_NAME\")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME; } } if (Z_STRLEN_PP(data) == sizeof(\"SCRIPT_FILENAME\")-1 && !strncmp(Z_STRVAL_PP(data), \"SCRIPT_FILENAME\", sizeof(\"SCRIPT_FILENAME\")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME; } } } \/* }}} *\/ \/* {{{ proto void Phar::interceptFileFuncs() * instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions * and return stat on files within the phar for relative paths * * Once called, this cannot be reversed, and continue until the end of the request. * * This allows legacy scripts to be pharred unmodified *\/ PHP_METHOD(Phar, interceptFileFuncs) { if (zend_parse_parameters_none() == FAILURE) { return; } phar_intercept_functions(TSRMLS_C); } \/* }}} *\/ \/* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]]) * Return a stub that can be used to run a phar-based archive without the phar extension * indexfile is the CLI startup filename, which defaults to \"index.php\", webindexfile * is the web startup filename, and also defaults to \"index.php\" *\/ PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *stub, *error; int index_len = 0, webindex_len = 0; size_t stub_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|ss\", &index, &index_len, &webindex, &webindex_len) == FAILURE) { return; } stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); return; } RETURN_STRINGL(stub, stub_len, 0); } \/* }}} *\/ \/* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]]) * Reads the currently executed file (a phar) and registers its manifest *\/ PHP_METHOD(Phar, mapPhar) { char *alias = NULL, *error; int alias_len = 0; long dataoffset = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s!l\", &alias, &alias_len, &dataoffset) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } } \/* }}} *\/ \/* {{{ proto mixed Phar::loadPhar(string filename [, string alias]) * Loads any phar archive with an alias *\/ PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; int fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|s!\", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } } \/* }}} *\/ \/* {{{ proto string Phar::apiVersion() * Returns the api version *\/ PHP_METHOD(Phar, apiVersion) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1); } \/* }}}*\/ \/* {{{ proto bool Phar::canCompress([int method]) * Returns whether phar extension supports compression using zlib\/bzip2 *\/ PHP_METHOD(Phar, canCompress) { long method = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|l\", &method) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (PHAR_G(has_zlib)) { RETURN_TRUE; } else { RETURN_FALSE; } case PHAR_ENT_COMPRESSED_BZ2: if (PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } default: if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } } } \/* }}} *\/ \/* {{{ proto bool Phar::canWrite() * Returns whether phar extension supports writing and creating phars *\/ PHP_METHOD(Phar, canWrite) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(!PHAR_G(readonly)); } \/* }}} *\/ \/* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true]) * Returns whether the given filename is a valid phar filename *\/ PHP_METHOD(Phar, isValidPharFilename) { char *fname; const char *ext_str; int fname_len, ext_len, is_executable; zend_bool executable = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|b\", &fname, &fname_len, &executable) == FAILURE) { return; } is_executable = executable; RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS); } \/* }}} *\/ #if HAVE_SPL \/** * from spl_directory *\/ static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) \/* {{{ *\/ { phar_archive_data *phar = (phar_archive_data *) object->oth; if (!phar->is_persistent) { phar_archive_delref(phar TSRMLS_CC); } object->oth = NULL; } \/* }}} *\/ \/** * from spl_directory *\/ static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) \/* {{{ *\/ { phar_archive_data *phar_data = (phar_archive_data *) dst->oth; if (!phar_data->is_persistent) { ++(phar_data->refcount); } } \/* }}} *\/ static spl_other_handler phar_spl_foreign_handler = { phar_spl_foreign_dtor, phar_spl_foreign_clone }; #endif \/* HAVE_SPL *\/ \/* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]]) * Construct a Phar archive object * * proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR]) * Construct a PharData archive object * * This function is used as the constructor for both the Phar and PharData * classes, hence the two prototypes above. *\/ PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, \"Cannot instantiate Phar object without SPL extension\"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|ls!l\", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|ls!\", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Cannot call constructor twice\"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { \/* use arch (the basename for the archive) for fname instead of fname *\/ \/* this allows support for RecursiveDirectoryIterator of subdirectories *\/ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"%s\", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Phar creation or opening failed\"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"PharData class can only be used for non-executable tar and zip archives\"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Phar class can only be used for executable tar and zip archives\"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, \"phar:\/\/%s%s\", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, \"phar:\/\/%s\", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, \"__construct\", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { \/* register this guy so we can modify if necessary *\/ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif \/* HAVE_SPL *\/ } \/* }}} *\/ \/* {{{ proto array Phar::getSupportedSignatures() * Return array of supported signature types *\/ PHP_METHOD(Phar, getSupportedSignatures) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); add_next_index_stringl(return_value, \"MD5\", 3, 1); add_next_index_stringl(return_value, \"SHA-1\", 5, 1); #ifdef PHAR_HASH_OK add_next_index_stringl(return_value, \"SHA-256\", 7, 1); add_next_index_stringl(return_value, \"SHA-512\", 7, 1); #endif #if PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, \"OpenSSL\", 7, 1); #else if (zend_hash_exists(&module_registry, \"openssl\", sizeof(\"openssl\"))) { add_next_index_stringl(return_value, \"OpenSSL\", 7, 1); } #endif } \/* }}} *\/ \/* {{{ proto array Phar::getSupportedCompression() * Return array of supported comparession algorithms *\/ PHP_METHOD(Phar, getSupportedCompression) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); phar_request_initialize(TSRMLS_C); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, \"GZ\", 2, 1); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, \"BZIP2\", 5, 1); } } \/* }}} *\/ \/* {{{ proto array Phar::unlinkArchive(string archive) * Completely remove a phar archive from memory and disk *\/ PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; int fname_len, zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown phar archive \\\"\\\"\"); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown phar archive \\\"%s\\\": %s\", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown phar archive \\\"%s\\\"\", fname); } return; } zname = (char*)zend_get_executed_filename(TSRMLS_C); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, \"phar:\/\/\", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar archive \\\"%s\\\" cannot be unlinked from within itself\", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar archive \\\"%s\\\" is in phar.cache_list, cannot unlinkArchive()\", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar archive \\\"%s\\\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()\", fname); return; } fname = estrndup(phar->fname, phar->fname_len); \/* invalidate phar cache *\/ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar TSRMLS_CC); unlink(fname); efree(fname); RETURN_TRUE; } \/* }}} *\/ #if HAVE_SPL #define PHAR_ARCHIVE_OBJECT() \\ phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \\ if (!phar_obj->arc.archive) { \\ zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \\ \"Cannot call method on an uninitialized Phar object\"); \\ return; \\ } \/* {{{ proto void Phar::__destruct() * if persistent, remove from the cache *\/ PHP_METHOD(Phar, __destruct) { phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) { zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive)); } } \/* }}} *\/ struct _phar_t { phar_archive_object *p; zend_class_entry *c; char *b; uint l; zval *ret; int count; php_stream *fp; }; static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) \/* {{{ *\/ { zval **value; zend_uchar key_type; zend_bool close_fp = 1; ulong int_key; struct _phar_t *p_obj = (struct _phar_t*) puser; uint str_key_len, base_len = p_obj->l, fname_len; phar_entry_data *data; php_stream *fp; size_t contents_len; char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL; phar_zstr key; char *str_key; zend_class_entry *ce = p_obj->c; phar_archive_object *phar_obj = p_obj->p; char *str = \"[stream]\"; iter->funcs->get_current_data(iter, &value TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (!value) { \/* failure in get_current_data *\/ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned no value\", ce->name); return ZEND_HASH_APPLY_STOP; } switch (Z_TYPE_PP(value)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(*(value) TSRMLS_CC); \/* break intentionally omitted *\/ #endif case IS_STRING: break; case IS_RESOURCE: php_stream_from_zval_no_verify(fp, value); if (!fp) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Iterator %v returned an invalid stream handle\", ce->name); return ZEND_HASH_APPLY_STOP; } if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid key (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { \/* IS_UNICODE == 10 *\/ #if PHP_VERSION_ID < 60000 \/* this can never happen, but fixes a compile warning *\/ spprintf(&str_key, 0, \"%s\", key); #else spprintf(&str_key, 0, \"%v\", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\\0') { str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid key (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } close_fp = 0; opened = (char *) estrndup(str, sizeof(\"[stream]\") - 1); goto after_open_fp; case IS_OBJECT: if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) { char *test = NULL; zval dummy; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC); if (!base_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Iterator %v returns an SplFileInfo object, so base directory must be specified\", ce->name); return ZEND_HASH_APPLY_STOP; } switch (intern->type) { case SPL_FS_DIR: #if PHP_VERSION_ID >= 60000 test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s; #elif PHP_VERSION_ID >= 50300 test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC); #else test = intern->path; #endif fname_len = spprintf(&fname, 0, \"%s%c%s\", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC); if (Z_BVAL(dummy)) { \/* ignore directories *\/ efree(fname); return ZEND_HASH_APPLY_KEEP; } test = expand_filepath(fname, NULL TSRMLS_CC); efree(fname); if (test) { fname = test; fname_len = strlen(fname); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Could not resolve file path\"); return ZEND_HASH_APPLY_STOP; } save = fname; goto phar_spl_fileinfo; case SPL_FS_INFO: case SPL_FS_FILE: #if PHP_VERSION_ID >= 60000 if (intern->file_name_type == IS_UNICODE) { zval zv; INIT_ZVAL(zv); Z_UNIVAL(zv) = intern->file_name; Z_UNILEN(zv) = intern->file_name_len; Z_TYPE(zv) = IS_UNICODE; zval_copy_ctor(&zv); zval_unicode_to_string(&zv TSRMLS_CC); fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC); ezfree(Z_UNIVAL(zv)); } else { fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC); } #else fname = expand_filepath(intern->file_name, NULL TSRMLS_CC); #endif if (!fname) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Could not resolve file path\"); return ZEND_HASH_APPLY_STOP; } fname_len = strlen(fname); save = fname; goto phar_spl_fileinfo; } } \/* fall-through *\/ default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid value (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } fname = Z_STRVAL_PP(value); fname_len = Z_STRLEN_PP(value); phar_spl_fileinfo: if (base_len) { temp = expand_filepath(base, NULL TSRMLS_CC); if (!temp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Could not resolve file path\"); if (save) { efree(save); } return ZEND_HASH_APPLY_STOP; } base = temp; base_len = strlen(base); if (strstr(fname, base)) { str_key_len = fname_len - base_len; if (str_key_len <= 0) { if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_KEEP; } str_key = fname + base_len; if (*str_key == '\/' || *str_key == '\\\\') { str_key++; str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned a path \\\"%s\\\" that is not in the base directory \\\"%s\\\"\", ce->name, fname, base); if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_STOP; } } else { if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid key (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { \/* IS_UNICODE == 10 *\/ #if PHP_VERSION_ID < 60000 \/* this can never happen, but fixes a compile warning *\/ spprintf(&str_key, 0, \"%s\", key); #else spprintf(&str_key, 0, \"%v\", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\\0') str_key_len--; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned an invalid key (must return a string)\", ce->name); return ZEND_HASH_APPLY_STOP; } } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned a path \\\"%s\\\" that safe mode prevents opening\", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned a path \\\"%s\\\" that open_basedir prevents opening\", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } \/* try to open source file, then create internal phar file and copy contents *\/ fp = php_stream_open_wrapper(fname, \"rb\", STREAM_MUST_SEEK|0, &opened); if (!fp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Iterator %v returned a file that could not be opened \\\"%s\\\"\", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } after_open_fp: if (str_key_len >= sizeof(\".phar\")-1 && !memcmp(str_key, \".phar\", sizeof(\".phar\")-1)) { \/* silently skip any files that would be added to the magic .phar directory *\/ if (save) { efree(save); } if (temp) { efree(temp); } if (opened) { efree(opened); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_KEEP; } if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, \"w+b\", 0, &error, 1 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Entry %s cannot be created: %s\", str_key, error); efree(error); if (save) { efree(save); } if (opened) { efree(opened); } if (temp) { efree(temp); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_STOP; } else { if (error) { efree(error); } \/* convert to PHAR_UFP *\/ if (data->internal_file->fp_type == PHAR_MOD) { php_stream_close(data->internal_file->fp); } data->internal_file->fp = NULL; data->internal_file->fp_type = PHAR_UFP; data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); data->fp = NULL; phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = php_stream_tell(p_obj->fp) - data->internal_file->offset; } if (close_fp) { php_stream_close(fp); } add_assoc_string(p_obj->ret, str_key, opened, 0); if (save) { efree(save); } if (temp) { efree(temp); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; phar_entry_delref(data TSRMLS_CC); return ZEND_HASH_APPLY_KEEP; } \/* }}} *\/ \/* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex]) * Construct a phar archive from an existing directory, recursively. * Optional second parameter is a regular expression for filtering directory contents. * * Return value is an array mapping phar index to actual files added. *\/ PHP_METHOD(Phar, buildFromDirectory) { char *dir, *error, *regex = NULL; int dir_len, regex_len = 0; zend_bool apply_reg = 0; zval arg, arg2, *iter, *iteriter, *regexiter = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot write to archive - write operations restricted by INI setting\"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|s\", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) { RETURN_FALSE; } MAKE_STD_ZVAL(iter); if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) { zval_ptr_dtor(&iter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate directory iterator for %s\", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg); ZVAL_STRINGL(&arg, dir, dir_len, 0); INIT_PZVAL(&arg2); #if PHP_VERSION_ID < 50300 ZVAL_LONG(&arg2, 0); #else ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS); #endif zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator, &spl_ce_RecursiveDirectoryIterator->constructor, \"__construct\", NULL, &arg, &arg2); if (EG(exception)) { zval_ptr_dtor(&iter); RETURN_FALSE; } MAKE_STD_ZVAL(iteriter); if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate directory iterator for %s\", phar_obj->arc.archive->fname); RETURN_FALSE; } zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator, &spl_ce_RecursiveIteratorIterator->constructor, \"__construct\", NULL, iter); if (EG(exception)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); RETURN_FALSE; } zval_ptr_dtor(&iter); if (regex_len > 0) { apply_reg = 1; MAKE_STD_ZVAL(regexiter); if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) { zval_ptr_dtor(&iteriter); zval_dtor(regexiter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate regex iterator for %s\", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg2); ZVAL_STRINGL(&arg2, regex, regex_len, 0); zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator, &spl_ce_RegexIterator->constructor, \"__construct\", NULL, iteriter, &arg2); } array_init(return_value); pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter); pass.p = phar_obj; pass.b = dir; pass.l = dir_len; pass.count = 0; pass.ret = return_value; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar \\\"%s\\\" unable to create temporary file\", phar_obj->arc.archive->fname); return; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(®exiter); } php_stream_close(pass.fp); zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar \\\"%s\\\" is persistent, unable to copy on write\", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(®exiter); } phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } } else { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(®exiter); } php_stream_close(pass.fp); } } \/* }}} *\/ \/* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory]) * Construct a phar archive from an iterator. The iterator must return a series of strings * that are full paths to files that should be added to the phar. The iterator key should * be the path that the file will have within the phar archive. * * If base directory is specified, then the key will be ignored, and instead the portion of * the current value minus the base directory will be used * * Returned is an array mapping phar index to actual file added *\/ PHP_METHOD(Phar, buildFromIterator) { zval *obj; char *error; uint base_len = 0; char *base = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot write out phar archive, phar is read-only\"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"O|s\", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar \\\"%s\\\" is persistent, unable to copy on write\", phar_obj->arc.archive->fname); return; } array_init(return_value); pass.c = Z_OBJCE_P(obj); pass.p = phar_obj; pass.b = base; pass.l = base_len; pass.ret = return_value; pass.count = 0; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"phar \\\"%s\\\": unable to create temporary file\", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"%s\", error); efree(error); } } else { php_stream_close(pass.fp); } } \/* }}} *\/ \/* {{{ proto int Phar::count() * Returns the number of entries in the Phar archive *\/ PHP_METHOD(Phar, count) { PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest)); } \/* }}} *\/ \/* {{{ proto bool Phar::isFileFormat(int format) * Returns true if the phar archive is based on the tar\/zip\/phar file format depending * on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in *\/ PHP_METHOD(Phar, isFileFormat) { long type; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &type) == FAILURE) { RETURN_FALSE; } switch (type) { case PHAR_FORMAT_TAR: RETURN_BOOL(phar_obj->arc.archive->is_tar); case PHAR_FORMAT_ZIP: RETURN_BOOL(phar_obj->arc.archive->is_zip); case PHAR_FORMAT_PHAR: RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip); default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"Unknown file format specified\"); } } \/* }}} *\/ static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) \/* {{{ *\/ { char *error; off_t offset; phar_entry_info *link; if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) { if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot convert phar archive \\\"%s\\\", unable to open entry \\\"%s\\\" contents: %s\", entry->phar->fname, entry->filename, error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot convert phar archive \\\"%s\\\", unable to open entry \\\"%s\\\" contents\", entry->phar->fname, entry->filename); } return FAILURE; } \/* copy old contents in entirety *\/ phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC); offset = php_stream_tell(fp); link = phar_get_link_source(entry TSRMLS_CC); if (!link) { link = entry; } if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot convert phar archive \\\"%s\\\", unable to copy entry \\\"%s\\\" contents\", entry->phar->fname, entry->filename); return FAILURE; } if (entry->fp_type == PHAR_MOD) { \/* save for potential restore on error *\/ entry->cfp = entry->fp; entry->fp = NULL; } \/* set new location of file contents *\/ entry->fp_type = PHAR_FP; entry->offset = offset; return SUCCESS; } \/* }}} *\/ static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) \/* {{{ *\/ { const char *oldname = NULL; char *oldpath = NULL; char *basename = NULL, *basepath = NULL; char *newname = NULL, *newpath = NULL; zval *ret, arg1; zend_class_entry *ce; char *error; const char *pcr_error; int ext_len = ext ? strlen(ext) : 0; int oldname_len; phar_archive_data **pphar = NULL; php_stream_statbuf ssb; if (!ext) { if (phar->is_zip) { if (phar->is_data) { ext = \"zip\"; } else { ext = \"phar.zip\"; } } else if (phar->is_tar) { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: if (phar->is_data) { ext = \"tar.gz\"; } else { ext = \"phar.tar.gz\"; } break; case PHAR_FILE_COMPRESSED_BZ2: if (phar->is_data) { ext = \"tar.bz2\"; } else { ext = \"phar.tar.bz2\"; } break; default: if (phar->is_data) { ext = \"tar\"; } else { ext = \"phar.tar\"; } } } else { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: ext = \"phar.gz\"; break; case PHAR_FILE_COMPRESSED_BZ2: ext = \"phar.bz2\"; break; default: ext = \"phar\"; } } } else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) { if (phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar converted from \\\"%s\\\" has invalid extension %s\", phar->fname, ext); } return NULL; } if (ext[0] == '.') { ++ext; } oldpath = estrndup(phar->fname, phar->fname_len); oldname = zend_memrchr(phar->fname, '\/', phar->fname_len); ++oldname; oldname_len = strlen(oldname); basename = estrndup(oldname, oldname_len); spprintf(&newname, 0, \"%s.%s\", strtok(basename, \".\"), ext); efree(basename); basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len)); phar->fname_len = spprintf(&newpath, 0, \"%s%s\", basepath, newname); phar->fname = newpath; phar->ext = newpath + phar->fname_len - strlen(ext) - 1; efree(basepath); efree(newname); if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, new phar name is in phar.cache_list\", phar->fname); return NULL; } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) { if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) { if (!zend_hash_num_elements(&phar->manifest)) { (*pphar)->is_tar = phar->is_tar; (*pphar)->is_zip = phar->is_zip; (*pphar)->is_data = phar->is_data; (*pphar)->flags = phar->flags; (*pphar)->fp = phar->fp; phar->fp = NULL; phar_destroy_phar_data(phar TSRMLS_CC); phar = *pphar; phar->refcount++; newpath = oldpath; goto its_ok; } } efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars, a phar with that name already exists\", phar->fname); return NULL; } its_ok: if (SUCCESS == php_stream_stat_path(newpath, &ssb)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" exists and must be unlinked prior to conversion\", newpath); efree(oldpath); return NULL; } if (!phar->is_data) { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext); return NULL; } if (phar->alias) { if (phar->is_temporary_alias) { phar->alias = NULL; phar->alias_len = 0; } else { phar->alias = estrndup(newpath, strlen(newpath)); phar->alias_len = strlen(newpath); phar->is_temporary_alias = 1; zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL); } } } else { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"data phar \\\"%s\\\" has invalid extension %s\", phar->fname, ext); return NULL; } phar->alias = NULL; phar->alias_len = 0; } if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to add newly converted phar \\\"%s\\\" to the list of phars\", phar->fname); return NULL; } phar_flush(phar, 0, 0, 1, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"%s\", error); efree(error); efree(oldpath); return NULL; } efree(oldpath); if (phar->is_data) { ce = phar_ce_data; } else { ce = phar_ce_archive; } MAKE_STD_ZVAL(ret); if (SUCCESS != object_init_ex(ret, ce)) { zval_dtor(ret); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Unable to instantiate phar object when converting archive \\\"%s\\\"\", phar->fname); return NULL; } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0); zend_call_method_with_1_params(&ret, ce, &ce->constructor, \"__construct\", NULL, &arg1); return ret; } \/* }}} *\/ static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) \/* {{{ *\/ { phar_archive_data *phar; phar_entry_info *entry, newentry; zval *ret; \/* invalidate phar cache *\/ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data)); \/* set whole-archive compression and type from parameter *\/ phar->flags = flags; phar->is_data = source->is_data; switch (convert) { case PHAR_FORMAT_TAR: phar->is_tar = 1; break; case PHAR_FORMAT_ZIP: phar->is_zip = 1; break; default: phar->is_data = 0; break; } zend_hash_init(&(phar->manifest), sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&phar->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&phar->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); phar->fp = php_stream_fopen_tmpfile(); if (phar->fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, \"unable to create temporary file\"); return NULL; } phar->fname = source->fname; phar->fname_len = source->fname_len; phar->is_temporary_alias = source->is_temporary_alias; phar->alias = source->alias; if (source->metadata) { zval *t; t = source->metadata; ALLOC_ZVAL(phar->metadata); *phar->metadata = *t; zval_copy_ctor(phar->metadata); #if PHP_VERSION_ID < 50300 phar->metadata->refcount = 1; #else Z_SET_REFCOUNT_P(phar->metadata, 1); #endif phar->metadata_len = 0; } \/* first copy each file's uncompressed contents to a temporary file and set per-file flags *\/ for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) { if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Cannot convert phar archive \\\"%s\\\"\", source->fname); return NULL; } newentry = *entry; if (newentry.link) { newentry.link = estrdup(newentry.link); goto no_copy; } if (newentry.tmp) { newentry.tmp = estrdup(newentry.tmp); goto no_copy; } newentry.metadata_str.c = 0; if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); \/* exception already thrown *\/ return NULL; } no_copy: newentry.filename = estrndup(newentry.filename, newentry.filename_len); if (newentry.metadata) { zval *t; t = newentry.metadata; ALLOC_ZVAL(newentry.metadata); *newentry.metadata = *t; zval_copy_ctor(newentry.metadata); #if PHP_VERSION_ID < 50300 newentry.metadata->refcount = 1; #else Z_SET_REFCOUNT_P(newentry.metadata, 1); #endif newentry.metadata_str.c = NULL; newentry.metadata_str.len = 0; } newentry.is_zip = phar->is_zip; newentry.is_tar = phar->is_tar; if (newentry.is_tar) { newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE); } newentry.is_modified = 1; newentry.phar = phar; newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; \/* remove compression from old_flags *\/ phar_set_inode(&newentry TSRMLS_CC); zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL); phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC); } if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) { return ret; } else { zend_hash_destroy(&(phar->manifest)); zend_hash_destroy(&(phar->mounted_dirs)); zend_hash_destroy(&(phar->virtual_dirs)); if (phar->fp) { php_stream_close(phar->fp); } efree(phar->fname); efree(phar); return NULL; \/* }}} *\/","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":42707,"input":"void CLASS adobe_coeff (const char *make, const char *model) { static const struct { const char *prefix; short black, maximum, trans[12]; } table[] = { { \"AGFAPHOTO DC-833m\", 0, 0, \/* DJC *\/ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { \"Apple QuickTake\", 0, 0, \/* DJC *\/ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, { \"Canon EOS D2000\", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { \"Canon EOS D6000\", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { \"Canon EOS D30\", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { \"Canon EOS D60\", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { \"Canon EOS 5D Mark II\", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { \"Canon EOS 5D\", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { \"Canon EOS 7D\", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { \"Canon EOS 10D\", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { \"Canon EOS 20Da\", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { \"Canon EOS 20D\", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { \"Canon EOS 30D\", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { \"Canon EOS 40D\", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { \"Canon EOS 50D\", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { \"Canon EOS 60D\", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { \"Canon EOS 300D\", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { \"Canon EOS 350D\", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { \"Canon EOS 400D\", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { \"Canon EOS 450D\", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { \"Canon EOS 500D\", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { \"Canon EOS 550D\", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { \"Canon EOS 600D\", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { \"Canon EOS 1000D\", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { \"Canon EOS 1100D\", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { \"Canon EOS-1Ds Mark III\", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { \"Canon EOS-1Ds Mark II\", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { \"Canon EOS-1D Mark IV\", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { \"Canon EOS-1D Mark III\", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { \"Canon EOS-1D Mark II N\", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { \"Canon EOS-1D Mark II\", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { \"Canon EOS-1DS\", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { \"Canon EOS-1D\", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { \"Canon EOS\", 0, 0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { \"Canon PowerShot A530\", 0, 0, { 0 } }, \/* don't want the A5 matrix *\/ { \"Canon PowerShot A50\", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { \"Canon PowerShot A5\", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { \"Canon PowerShot G10\", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { \"Canon PowerShot G11\", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { \"Canon PowerShot G12\", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { \"Canon PowerShot G1\", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { \"Canon PowerShot G2\", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { \"Canon PowerShot G3\", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { \"Canon PowerShot G5\", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { \"Canon PowerShot G6\", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { \"Canon PowerShot G9\", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { \"Canon PowerShot Pro1\", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { \"Canon PowerShot Pro70\", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { \"Canon PowerShot Pro90\", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { \"Canon PowerShot S30\", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { \"Canon PowerShot S40\", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { \"Canon PowerShot S45\", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { \"Canon PowerShot S50\", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { \"Canon PowerShot S60\", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { \"Canon PowerShot S70\", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { \"Canon PowerShot S90\", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { \"Canon PowerShot S95\", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { \"Canon PowerShot S100\", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { \"Canon PowerShot A470\", 0, 0, \/* DJC *\/ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { \"Canon PowerShot A610\", 0, 0, \/* DJC *\/ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { \"Canon PowerShot A620\", 0, 0, \/* DJC *\/ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { \"Canon PowerShot A630\", 0, 0, \/* DJC *\/ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { \"Canon PowerShot A640\", 0, 0, \/* DJC *\/ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { \"Canon PowerShot A650\", 0, 0, \/* DJC *\/ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { \"Canon PowerShot A720\", 0, 0, \/* DJC *\/ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { \"Canon PowerShot S3 IS\", 0, 0, \/* DJC *\/ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { \"Canon PowerShot SX1 IS\", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { \"Canon PowerShot SX110 IS\", 0, 0, \/* DJC *\/ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { \"CASIO EX-S20\", 0, 0, \/* DJC *\/ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { \"CASIO EX-Z750\", 0, 0, \/* DJC *\/ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { \"CASIO EX-Z10\", 128, 0xfff, \/* DJC *\/ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { \"CINE 650\", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { \"CINE 660\", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { \"CINE\", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { \"Contax N Digital\", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { \"EPSON R-D1\", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { \"FUJIFILM FinePix E550\", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { \"FUJIFILM FinePix E900\", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { \"FUJIFILM FinePix F8\", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { \"FUJIFILM FinePix F7\", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { \"FUJIFILM FinePix S100FS\", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { \"FUJIFILM FinePix S200EXR\", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { \"FUJIFILM FinePix S20Pro\", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { \"FUJIFILM FinePix S2Pro\", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { \"FUJIFILM FinePix S3Pro\", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { \"FUJIFILM FinePix S5Pro\", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { \"FUJIFILM FinePix S5000\", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { \"FUJIFILM FinePix S5100\", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { \"FUJIFILM FinePix S5500\", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { \"FUJIFILM FinePix S5200\", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { \"FUJIFILM FinePix S5600\", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { \"FUJIFILM FinePix S6\", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { \"FUJIFILM FinePix S7000\", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { \"FUJIFILM FinePix S9000\", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { \"FUJIFILM FinePix S9500\", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { \"FUJIFILM FinePix S9100\", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { \"FUJIFILM FinePix S9600\", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { \"FUJIFILM IS-1\", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { \"FUJIFILM IS Pro\", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { \"FUJIFILM FinePix HS10 HS11\", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { \"FUJIFILM FinePix HS20EXR\", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { \"FUJIFILM FinePix F550EXR\", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { \"FUJIFILM FinePix F600EXR\", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { \"FUJIFILM FinePix X100\", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { \"FUJIFILM X10\", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { \"Imacon Ixpress\", 0, 0, \/* DJC *\/ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { \"KODAK NC2000\", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { \"Kodak DCS315C\", 8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { \"Kodak DCS330C\", 8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { \"KODAK DCS420\", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { \"KODAK DCS460\", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { \"KODAK EOSDCS1\", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { \"KODAK EOSDCS3B\", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { \"Kodak DCS520C\", 180, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { \"Kodak DCS560C\", 188, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { \"Kodak DCS620C\", 180, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { \"Kodak DCS620X\", 185, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { \"Kodak DCS660C\", 214, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { \"Kodak DCS720X\", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { \"Kodak DCS760C\", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { \"Kodak DCS Pro SLR\", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { \"Kodak DCS Pro 14nx\", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { \"Kodak DCS Pro 14\", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { \"Kodak ProBack645\", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { \"Kodak ProBack\", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { \"KODAK P712\", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { \"KODAK P850\", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { \"KODAK P880\", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { \"KODAK EasyShare Z980\", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { \"KODAK EasyShare Z981\", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { \"KODAK EasyShare Z990\", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { \"KODAK EASYSHARE Z1015\", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { \"Leaf CMost\", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { \"Leaf Valeo 6\", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { \"Leaf Aptus 54S\", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { \"Leaf Aptus 65\", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { \"Leaf Aptus 75\", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { \"Leaf\", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { \"Mamiya ZD\", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { \"Micron 2010\", 110, 0, \/* DJC *\/ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { \"Minolta DiMAGE 5\", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { \"Minolta DiMAGE 7Hi\", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { \"Minolta DiMAGE 7\", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { \"Minolta DiMAGE A1\", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { \"MINOLTA DiMAGE A200\", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { \"Minolta DiMAGE A2\", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { \"Minolta DiMAGE Z2\", 0, 0, \/* DJC *\/ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { \"MINOLTA DYNAX 5\", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { \"MINOLTA DYNAX 7\", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { \"MOTOROLA PIXL\", 0, 0, \/* DJC *\/ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { \"NIKON D100\", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { \"NIKON D1H\", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { \"NIKON D1X\", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { \"NIKON D1\", 0, 0, \/* multiplied by 2.218750, 1.0, 1.148438 *\/ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { \"NIKON D200\", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { \"NIKON D2H\", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { \"NIKON D2X\", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { \"NIKON D3000\", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { \"NIKON D3100\", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { \"NIKON D300\", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { \"NIKON D3X\", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { \"NIKON D3S\", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { \"NIKON D3\", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { \"NIKON D40X\", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { \"NIKON D40\", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { \"NIKON D5000\", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { \"NIKON D5100\", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { \"NIKON D50\", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { \"NIKON D60\", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { \"NIKON D7000\", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { \"NIKON D700\", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { \"NIKON D70\", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { \"NIKON D80\", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { \"NIKON D90\", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { \"NIKON E950\", 0, 0x3dd, \/* DJC *\/ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { \"NIKON E995\", 0, 0, \/* copied from E5000 *\/ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { \"NIKON E2100\", 0, 0, \/* copied from Z2, new white balance *\/ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711} }, { \"NIKON E2500\", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { \"NIKON E3200\", 0, 0, \/* DJC *\/ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { \"NIKON E4300\", 0, 0, \/* copied from Minolta DiMAGE Z2 *\/ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { \"NIKON E4500\", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { \"NIKON E5000\", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { \"NIKON E5400\", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { \"NIKON E5700\", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { \"NIKON E8400\", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { \"NIKON E8700\", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { \"NIKON E8800\", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { \"NIKON COOLPIX P6000\", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { \"NIKON COOLPIX P7000\", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { \"NIKON COOLPIX P7100\", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { \"NIKON 1 \", 0, 0, { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { \"OLYMPUS C5050\", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { \"OLYMPUS C5060\", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { \"OLYMPUS C7070\", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { \"OLYMPUS C70\", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { \"OLYMPUS C80\", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { \"OLYMPUS E-10\", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { \"OLYMPUS E-1\", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { \"OLYMPUS E-20\", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { \"OLYMPUS E-300\", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { \"OLYMPUS E-330\", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { \"OLYMPUS E-30\", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { \"OLYMPUS E-3\", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { \"OLYMPUS E-400\", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { \"OLYMPUS E-410\", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { \"OLYMPUS E-420\", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { \"OLYMPUS E-450\", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { \"OLYMPUS E-500\", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { \"OLYMPUS E-510\", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { \"OLYMPUS E-520\", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { \"OLYMPUS E-5\", 0, 0, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { \"OLYMPUS E-600\", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { \"OLYMPUS E-620\", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { \"OLYMPUS E-P1\", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { \"OLYMPUS E-P2\", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { \"OLYMPUS E-P3\", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { \"OLYMPUS E-PL1s\", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { \"OLYMPUS E-PL1\", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { \"OLYMPUS E-PL2\", 0, 0, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { \"OLYMPUS E-PL3\", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { \"OLYMPUS E-PM1\", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { \"OLYMPUS SP350\", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { \"OLYMPUS SP3\", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { \"OLYMPUS SP500UZ\", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { \"OLYMPUS SP510UZ\", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { \"OLYMPUS SP550UZ\", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { \"OLYMPUS SP560UZ\", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { \"OLYMPUS SP570UZ\", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { \"OLYMPUS XZ-1\", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { \"PENTAX *ist DL2\", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { \"PENTAX *ist DL\", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { \"PENTAX *ist DS2\", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { \"PENTAX *ist DS\", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { \"PENTAX *ist D\", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { \"PENTAX K10D\", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { \"PENTAX K1\", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { \"PENTAX K20D\", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { \"PENTAX K200D\", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { \"PENTAX K2000\", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { \"PENTAX K-m\", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { \"PENTAX K-x\", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { \"PENTAX K-r\", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { \"PENTAX K-5\", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { \"PENTAX K-7\", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { \"PENTAX 645D\", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { \"Panasonic DMC-FZ8\", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { \"Panasonic DMC-FZ18\", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { \"Panasonic DMC-FZ28\", 15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { \"Panasonic DMC-FZ30\", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { \"Panasonic DMC-FZ3\", 143, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { \"Panasonic DMC-FZ4\", 143, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { \"Panasonic DMC-FZ50\", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { \"LEICA V-LUX1\", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { \"Panasonic DMC-L10\", 15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { \"Panasonic DMC-L1\", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { \"LEICA DIGILUX 3\", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { \"Panasonic DMC-LC1\", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { \"LEICA DIGILUX 2\", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { \"Panasonic DMC-LX1\", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { \"LEICA D-LUX2\", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { \"Panasonic DMC-LX2\", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { \"LEICA D-LUX3\", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { \"Panasonic DMC-LX3\", 15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { \"LEICA D-LUX 4\", 15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { \"Panasonic DMC-LX5\", 143, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { \"LEICA D-LUX 5\", 143, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { \"Panasonic DMC-FZ100\", 143, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { \"LEICA V-LUX 2\", 143, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { \"Panasonic DMC-FZ150\", 143, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { \"LEICA V-LUX 3\", 143, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { \"Panasonic DMC-FX150\", 15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { \"Panasonic DMC-G10\", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { \"Panasonic DMC-G1\", 15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { \"Panasonic DMC-G2\", 15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { \"Panasonic DMC-G3\", 143, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { \"Panasonic DMC-GF1\", 15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { \"Panasonic DMC-GF2\", 143, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { \"Panasonic DMC-GF3\", 143, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { \"Panasonic DMC-GH1\", 15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { \"Panasonic DMC-GH2\", 15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { \"Panasonic DMC-GX1\", 143, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { \"Phase One H 20\", 0, 0, \/* DJC *\/ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { \"Phase One H 25\", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { \"Phase One P 2\", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { \"Phase One P 30\", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { \"Phase One P 45\", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { \"Phase One P40\", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { \"Phase One P65\", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { \"RED ONE\", 704, 0xffff, \/* DJC *\/ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { \"SAMSUNG EX1\", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { \"SAMSUNG NX200\", 0, 0xfff, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { \"SAMSUNG NX\", 0, 0, \/* NX5, NX10, NX11, NX100 *\/ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { \"SAMSUNG WB2000\", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { \"SAMSUNG GX-1\", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { \"SAMSUNG S85\", 0, 0xffff, \/* DJC *\/ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, { \"Sinar\", 0, 0, \/* DJC *\/ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { \"SONY DSC-F828\", 491, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { \"SONY DSC-R1\", 512, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { \"SONY DSC-V3\", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, { \"SONY DSLR-A100\", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { \"SONY DSLR-A290\", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { \"SONY DSLR-A2\", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { \"SONY DSLR-A300\", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { \"SONY DSLR-A330\", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { \"SONY DSLR-A350\", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { \"SONY DSLR-A380\", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { \"SONY DSLR-A390\", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { \"SONY DSLR-A450\", 128, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { \"SONY DSLR-A580\", 128, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { \"SONY DSLR-A5\", 128, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { \"SONY DSLR-A700\", 126, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { \"SONY DSLR-A850\", 128, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { \"SONY DSLR-A900\", 128, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { \"SONY NEX-5N\", 128, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { \"SONY NEX-C3\", 128, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { \"SONY NEX-3\", 138, 0, \/* DJC *\/ { 6907,-1256,-645,-4940,12621,2320,-1710,2581,6230 } }, { \"SONY NEX-5\", 116, 0, \/* DJC *\/ { 6807,-1350,-342,-4216,11649,2567,-1089,2001,6420 } }, { \"SONY NEX-3\", 128, 0, \/* Adobe *\/ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { \"SONY NEX-5\", 128, 0, \/* Adobe *\/ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { \"SONY NEX-7\", 128, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { \"SONY SLT-A33\", 128, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { \"SONY SLT-A35\", 128, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { \"SONY SLT-A55\", 128, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { \"SONY SLT-A65\", 128, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { \"SONY SLT-A77\", 128, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } } }; double cam_xyz[4][3]; char name[130]; int i, j, k; sprintf (name, \"%s %s\", make, model); for (i=0; i < (int) sizeof table \/ (int) sizeof *table; i++) if (!strncmp (name, table[i].prefix, strlen(table[i].prefix))) { if (table[i].black) black = (ushort) table[i].black; if (table[i].maximum) maximum = (ushort) table[i].maximum; if (table[i].trans[0]) { for (j=0; j < 4; j++) for (k=0; k < 3; k++) cam_xyz[j][k] = table[i].trans[3*j+k] \/ 10000.0; cam_xyz_coeff (cam_xyz); } break; } }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":160077,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char s[2]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); if (image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError, \"MemoryAllocationFailed\"); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *s; register Quantum *q, *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,q) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image, q, opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (Magick_png_color_equal(image,q,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image, q, opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,q) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image, q, transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,q); ping_trans_color.green=(unsigned short) GetPixelGreen(image,q); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,q); ping_trans_color.gray=(unsigned short) GetPixelGray(image,q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (Magick_png_color_equal(image,q,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,q,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,q,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (Magick_png_color_equal(image,q,semitransparent+i) && GetPixelAlpha(image,q) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image, q, semitransparent+i); } } } q+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != GetPixelGreen(image,s) || GetPixelRed(image,s) != GetPixelBlue(image,s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,s) != 0 && GetPixelRed(image,s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) ThrowWriterException(ResourceLimitError, \"MemoryAllocationFailed\"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,r); SetPixelAlpha(image,TransparentAlpha,r); } else SetPixelAlpha(image,OpaqueAlpha,r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR04PixelRGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR03RGB(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,r) == OpaqueAlpha) LBR02PixelBlue(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 && GetPixelAlpha(image,r) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),r); } r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } \/* write any png-chunk-b profiles *\/ (void) Magick_png_write_chunk_from_profile(image,\"PNG-chunk-b\",logging); png_write_info(ping,ping_info); \/* write any PNG-chunk-m profiles *\/ (void) Magick_png_write_chunk_from_profile(image,\"PNG-chunk-m\",logging); ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif \/* write vpAg chunk (deprecated, replaced by caNv) *\/ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); \/* data length=8 *\/ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; \/* unit = pixels *\/ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { \/* Palette, Bilevel, or Opaque Monochrome *\/ register const Quantum *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { \/* Undo pixel scaling *\/ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write any PNG-chunk-e profiles *\/ (void) Magick_png_write_chunk_from_profile(image,\"PNG-chunk-e\",logging); \/* write exIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":233149,"input":"static void ndpi_init_protocol_defaults(struct ndpi_detection_module_struct *ndpi_str) { ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS]; u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO}, custom_master[2]; \/* Reset all settings *\/ memset(ndpi_str->proto_defaults, 0, sizeof(ndpi_str->proto_defaults)); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNRATED, NDPI_PROTOCOL_UNKNOWN, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Unknown\", NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_FTP_CONTROL, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"FTP_CONTROL\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 21, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_FTP_DATA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"FTP_DATA\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 20, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MAIL_POP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"POP3\", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 110, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_POPS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"POPS\", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 995, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MAIL_SMTP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SMTP\", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 25, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_SMTPS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SMTPS\", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 465, 587, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MAIL_IMAP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IMAP\", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 143, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_IMAPS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IMAPS\", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 993, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DNS, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"DNS\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 53, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 53, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IPP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IPP\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IMO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IMO\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"HTTP\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 80, 0 \/* ntop *\/, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MDNS, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"MDNS\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 5353, 5354, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NTP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"NTP\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 123, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NETBIOS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"NetBIOS\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 139, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 137, 138, 139, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NFS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"NFS\", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 2049, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 2049, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SSDP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SSDP\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BGP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"BGP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 179, 2605, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SNMP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SNMP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 161, 162, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_XDMCP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"XDMCP\", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 177, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 177, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_DANGEROUS, NDPI_PROTOCOL_SMBV1, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SMBv1\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 445, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SYSLOG, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Syslog\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 514, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 514, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DHCP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"DHCP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 67, 68, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_POSTGRES, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"PostgreSQL\", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 5432, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MYSQL, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"MySQL\", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 3306, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_DIRECT_DOWNLOAD_LINK, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Direct_Download_Link\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_APPLEJUICE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"AppleJuice\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_DIRECTCONNECT, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"DirectConnect\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NATS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Nats\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_NTOP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"ntop\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VMWARE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"VMware\", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 903, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 902, 903, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_FBZERO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"FacebookZero\", NDPI_PROTOCOL_CATEGORY_SOCIAL_NETWORK, ndpi_build_default_ports(ports_a, 443, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_KONTIKI, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Kontiki\", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_OPENFT, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"OpenFT\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_FASTTRACK, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"FastTrack\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_GNUTELLA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Gnutella\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_EDONKEY, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"eDonkey\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_BITTORRENT, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"BitTorrent\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 51413, 53646, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 6771, 51413, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKYPE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Skype\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKYPE_CALL, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SkypeCall\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TIKTOK, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"TikTok\", NDPI_PROTOCOL_CATEGORY_SOCIAL_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEREDO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Teredo\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 3544, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WECHAT, 0 \/* can_have_a_subprotocol *\/, no_master, \/* wechat.com *\/ no_master, \"WeChat\", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MEMCACHED, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Memcached\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 11211, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 11211, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SMBV23, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SMBv23\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 445, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MINING, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Mining\", CUSTOM_CATEGORY_MINING, ndpi_build_default_ports(ports_a, 8333, 30303, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NEST_LOG_SINK, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"NestLogSink\", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 11095, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MODBUS, 1 \/* no subprotocol *\/, no_master, no_master, \"Modbus\", NDPI_PROTOCOL_CATEGORY_NETWORK, \/* Perhaps IoT in the future *\/ ndpi_build_default_ports(ports_a, 502, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP_CALL, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"WhatsAppCall\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DATASAVER, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"DataSaver\", NDPI_PROTOCOL_CATEGORY_WEB \/* dummy *\/, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SIGNAL, 0 \/* can_have_a_subprotocol *\/, no_master, \/* https:\/\/signal.org *\/ no_master, \"Signal\", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DOH_DOT, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"DoH_DoT\", NDPI_PROTOCOL_CATEGORY_NETWORK \/* dummy *\/, ndpi_build_default_ports(ports_a, 853, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FREE_205, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"FREE_205\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WIREGUARD, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"WireGuard\", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 51820, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPSTREAM, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"PPStream\", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_XBOX, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Xbox\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 3074, 3076, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 3074, 3076, 500, 3544, 4500) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PLAYSTATION, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Playstation\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 1935, 3478, 3479, 3480, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 3478, 3479, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_QQ, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"QQ\", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_RTSP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"RTSP\", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 554, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 554, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ICECAST, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IceCast\", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPLIVE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"PPLive\", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPSTREAM, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"PPStream\", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ZATTOO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Zattoo\", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SHOUTCAST, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"ShoutCast\", NDPI_PROTOCOL_CATEGORY_MUSIC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SOPCAST, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Sopcast\", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TVANTS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Tvants\", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TVUPLAYER, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"TVUplayer\", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_DOWNLOAD, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"HTTP_Download\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_QQLIVE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"QQLive\", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_THUNDER, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Thunder\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SOULSEEK, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Soulseek\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PS_VUE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"PS_VUE\", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_IRC, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IRC\", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 194, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 194, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AYIYA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Ayiya\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 5072, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UNENCRYPTED_JABBER, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Unencrypted_Jabber\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_OSCAR, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Oscar\", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_BATTLEFIELD, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"BattleField\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_VRRP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"VRRP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_STEAM, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Steam\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_HALFLIFE2, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"HalfLife2\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WORLDOFWARCRAFT, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"WorldOfWarcraft\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_HOTSPOT_SHIELD, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"HotspotShield\", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_TELNET, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Telnet\", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 23, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); custom_master[0] = NDPI_PROTOCOL_SIP, custom_master[1] = NDPI_PROTOCOL_H323; ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_STUN, 0 \/* can_have_a_subprotocol *\/, no_master, custom_master, \"STUN\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 3478, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_IP_IPSEC, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IPsec\", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 500, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 500, 4500, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_GRE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"GRE\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_ICMP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"ICMP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_IGMP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IGMP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_EGP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"EGP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_SCTP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SCTP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_OSPF, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"OSPF\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 2604, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_IP_IN_IP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IP_in_IP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"RTP\", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RDP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"RDP\", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 3389, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 3389, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VNC, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"VNC\", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 5900, 5901, 5800, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PCANYWHERE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"PcAnywhere\", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZOOM, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Zoom\", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP_FILES, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"WhatsAppFiles\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"WhatsApp\", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_TLS, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"TLS\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 443, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SSH, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SSH\", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 22, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_USENET, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Usenet\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MGCP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"MGCP\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IAX, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"IAX\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 4569, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 4569, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AFP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"AFP\", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 548, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 548, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_HULU, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Hulu\", NDPI_PROTOCOL_CATEGORY_STREAMING, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CHECKMK, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"CHECKMK\", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 6556, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_STEALTHNET, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Stealthnet\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_AIMINI, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Aimini\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SIP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SIP\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 5060, 5061, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 5060, 5061, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TRUPHONE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"TruPhone\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_ICMPV6, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"ICMPV6\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DHCPV6, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"DHCPV6\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ARMAGETRON, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Armagetron\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_CROSSFIRE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Crossfire\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DOFUS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Dofus\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FIESTA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Fiesta\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FLORENSIA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Florensia\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_GUILDWARS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Guildwars\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_ACTIVESYNC, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"HTTP_ActiveSync\", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_KERBEROS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Kerberos\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 88, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 88, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LDAP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"LDAP\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 389, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 389, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_MAPLESTORY, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"MapleStory\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MSSQL_TDS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"MsSQL-TDS\", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 1433, 1434, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PPTP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"PPTP\", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WARCRAFT3, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Warcraft3\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WORLD_OF_KUNG_FU, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"WorldOfKungFu\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DCERPC, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"DCE_RPC\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 135, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NETFLOW, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"NetFlow\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 2055, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SFLOW, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"sFlow\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 6343, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_CONNECT, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"HTTP_Connect\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_PROXY, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"HTTP_Proxy\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 8080, 3128, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CITRIX, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Citrix\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 1494, 2598, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WEBEX, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Webex\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RADIUS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Radius\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 1812, 1813, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 1812, 1813, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEAMVIEWER, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"TeamViewer\", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 5938, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 5938, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LOTUS_NOTES, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"LotusNotes\", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE, ndpi_build_default_ports(ports_a, 1352, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SAP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SAP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 3201, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); \/* Missing dissector: port based only *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_GTP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"GTP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 2152, 2123, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UPNP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"UPnP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 1780, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 1900, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TELEGRAM, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Telegram\", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_QUIC, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"QUIC\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 443, 80, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DIAMETER, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Diameter\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 3868, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_APPLE_PUSH, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"ApplePush\", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DROPBOX, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Dropbox\", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 17500, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SPOTIFY, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Spotify\", NDPI_PROTOCOL_CATEGORY_MUSIC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MESSENGER, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Messenger\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LISP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"LISP\", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 4342, 4341, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_EAQ, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"EAQ\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 6000, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_KAKAOTALK_VOICE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"KakaoTalk_Voice\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_MPEGTS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"MPEG_TS\", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); \/* http:\/\/en.wikipedia.org\/wiki\/Link-local_Multicast_Name_Resolution *\/ ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LLMNR, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"LLMNR\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 5355, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 5355, 0, 0, 0, 0) \/* UDP *\/); \/* Missing dissector: port based only *\/ ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_REMOTE_SCAN, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"RemoteScan\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 6077, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 6078, 0, 0, 0, 0) \/* UDP *\/); \/* Missing dissector: port based only *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_H323, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"H323\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 1719, 1720, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 1719, 1720, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_OPENVPN, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"OpenVPN\", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 1194, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 1194, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NOE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"NOE\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CISCOVPN, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"CiscoVPN\", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 10000, 8008, 8009, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 10000, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEAMSPEAK, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"TeamSpeak\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKINNY, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"CiscoSkinny\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 2000, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTCP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"RTCP\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RSYNC, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"RSYNC\", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 873, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ORACLE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Oracle\", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 1521, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CORBA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Corba\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UBUNTUONE, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"UbuntuONE\", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHOIS_DAS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Whois-DAS\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 43, 4343, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_COLLECTD, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Collectd\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 25826, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SOCKS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SOCKS\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 1080, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 1080, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TFTP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"TFTP\", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 69, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTMP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"RTMP\", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 1935, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PANDO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Pando_Media_Booster\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MEGACO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Megaco\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 2944, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_REDIS, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Redis\", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 6379, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZMQ, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"ZeroMQ\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_VHUA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"VHUA\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 58267, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_STARCRAFT, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Starcraft\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 1119, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 1119, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_UBNTAC2, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"UBNTAC2\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 10001, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VIBER, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Viber\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 7985, 5242, 5243, 4244, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 7985, 7987, 5242, 5243, 4244)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_COAP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"COAP\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 5683, 5684, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MQTT, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"MQTT\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 1883, 8883, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SOMEIP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SOMEIP\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 30491, 30501, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 30491, 30501, 30490, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RX, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"RX\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_GIT, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Git\", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE, ndpi_build_default_ports(ports_a, 9418, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DRDA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"DRDA\", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HANGOUT_DUO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"GoogleHangoutDuo\", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BJNP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"BJNP\", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 8612, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SMPP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"SMPP\", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_OOKLA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Ookla\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AMQP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"AMQP\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_DNSCRYPT, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"DNScrypt\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), \/* TCP *\/ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); \/* UDP *\/ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TINC, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"TINC\", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 655, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 655, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_FIX, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"FIX\", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_NINTENDO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Nintendo\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_CSGO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"CSGO\", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AJP, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"AJP\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 8009, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TARGUS_GETDATA, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"Targus Dataspeed\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 5001, 5201, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 5001, 5201, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AMAZON_VIDEO, 0 \/* can_have_a_subprotocol *\/, no_master, no_master, \"AmazonVideo\", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DNP3, 1 \/* no subprotocol *\/, no_master, no_master, \"DNP3\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 20000, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IEC60870, 1 \/* no subprotocol *\/, no_master, no_master, \"IEC60870\", NDPI_PROTOCOL_CATEGORY_NETWORK, \/* Perhaps IoT in the future *\/ ndpi_build_default_ports(ports_a, 2404, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BLOOMBERG, 1 \/* no subprotocol *\/, no_master, no_master, \"Bloomberg\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CAPWAP, 1 \/* no subprotocol *\/, no_master, no_master, \"CAPWAP\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 5246, 5247, 0, 0, 0) \/* UDP *\/ ); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZABBIX, 1 \/* no subprotocol *\/, no_master, no_master, \"Zabbix\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 10050, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/ ); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_S7COMM, 1 \/* no subprotocol *\/, no_master, no_master, \"s7comm\", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 102, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MSTEAMS, 1 \/* no subprotocol *\/, no_master, no_master, \"Teams\", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/ ); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WEBSOCKET, 1 \/* can_have_a_subprotocol *\/, no_master, no_master, \"WebSocket\", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) \/* TCP *\/, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) \/* UDP *\/); #ifdef CUSTOM_NDPI_PROTOCOLS #include \"..\/..\/..\/nDPI-custom\/custom_ndpi_main.c\" #endif \/* calling function for host and content matched protocols *\/ init_string_based_protocols(ndpi_str); ndpi_validate_protocol_initialization(ndpi_str); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":463473,"input":"int cli_scanpe(cli_ctx *ctx) { uint16_t e_magic; \/* DOS signature (\"MZ\") *\/ uint16_t nsections; uint32_t e_lfanew; \/* address of new exe header *\/ uint32_t ep, vep; \/* entry point (raw, virtual) *\/ uint8_t polipos = 0; time_t timestamp; struct pe_image_file_hdr file_hdr; union { struct pe_image_optional_hdr64 opt64; struct pe_image_optional_hdr32 opt32; } pe_opt; struct pe_image_section_hdr *section_hdr; char sname[9], epbuff[4096], *tempfile; uint32_t epsize; ssize_t bytes, at; unsigned int i, found, upx_success = 0, min = 0, max = 0, err, overlays = 0; unsigned int ssize = 0, dsize = 0, dll = 0, pe_plus = 0, corrupted_cur; int (*upxfn)(char *, uint32_t, char *, uint32_t *, uint32_t, uint32_t, uint32_t) = NULL; char *src = NULL, *dest = NULL; int ndesc, ret = CL_CLEAN, upack = 0, native=0; size_t fsize; uint32_t valign, falign, hdr_size, j; struct cli_exe_section *exe_sections; struct cli_matcher *md5_sect; char timestr[32]; struct pe_image_data_dir *dirs; struct cli_bc_ctx *bc_ctx; fmap_t *map; struct cli_pe_hook_data pedata; #ifdef HAVE__INTERNAL__SHA_COLLECT int sha_collect = ctx->sha_collect; #endif const char * virname = NULL; uint32_t viruses_found = 0; if(!ctx) { cli_errmsg(\"cli_scanpe: ctx == NULL\\n\"); return CL_ENULLARG; } map = *ctx->fmap; if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic)) { cli_dbgmsg(\"Can't read DOS signature\\n\"); return CL_CLEAN; } if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) { cli_dbgmsg(\"Invalid DOS signature\\n\"); return CL_CLEAN; } if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) { cli_dbgmsg(\"Can't read new header address\\n\"); \/* truncated header? *\/ if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } e_lfanew = EC32(e_lfanew); cli_dbgmsg(\"e_lfanew == %d\\n\", e_lfanew); if(!e_lfanew) { cli_dbgmsg(\"Not a PE file\\n\"); return CL_CLEAN; } if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) { \/* bad information in e_lfanew - probably not a PE file *\/ cli_dbgmsg(\"Can't read file header\\n\"); return CL_CLEAN; } if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) { cli_dbgmsg(\"Invalid PE signature (probably NE file)\\n\"); return CL_CLEAN; } if(EC16(file_hdr.Characteristics) & 0x2000) { cli_dbgmsg(\"File type: DLL\\n\"); dll = 1; } else if(EC16(file_hdr.Characteristics) & 0x01) { cli_dbgmsg(\"File type: Executable\\n\"); } switch(EC16(file_hdr.Machine)) { case 0x0: cli_dbgmsg(\"Machine type: Unknown\\n\"); break; case 0x14c: cli_dbgmsg(\"Machine type: 80386\\n\"); break; case 0x14d: cli_dbgmsg(\"Machine type: 80486\\n\"); break; case 0x14e: cli_dbgmsg(\"Machine type: 80586\\n\"); break; case 0x160: cli_dbgmsg(\"Machine type: R30000 (big-endian)\\n\"); break; case 0x162: cli_dbgmsg(\"Machine type: R3000\\n\"); break; case 0x166: cli_dbgmsg(\"Machine type: R4000\\n\"); break; case 0x168: cli_dbgmsg(\"Machine type: R10000\\n\"); break; case 0x184: cli_dbgmsg(\"Machine type: DEC Alpha AXP\\n\"); break; case 0x284: cli_dbgmsg(\"Machine type: DEC Alpha AXP 64bit\\n\"); break; case 0x1f0: cli_dbgmsg(\"Machine type: PowerPC\\n\"); break; case 0x200: cli_dbgmsg(\"Machine type: IA64\\n\"); break; case 0x268: cli_dbgmsg(\"Machine type: M68k\\n\"); break; case 0x266: cli_dbgmsg(\"Machine type: MIPS16\\n\"); break; case 0x366: cli_dbgmsg(\"Machine type: MIPS+FPU\\n\"); break; case 0x466: cli_dbgmsg(\"Machine type: MIPS16+FPU\\n\"); break; case 0x1a2: cli_dbgmsg(\"Machine type: Hitachi SH3\\n\"); break; case 0x1a3: cli_dbgmsg(\"Machine type: Hitachi SH3-DSP\\n\"); break; case 0x1a4: cli_dbgmsg(\"Machine type: Hitachi SH3-E\\n\"); break; case 0x1a6: cli_dbgmsg(\"Machine type: Hitachi SH4\\n\"); break; case 0x1a8: cli_dbgmsg(\"Machine type: Hitachi SH5\\n\"); break; case 0x1c0: cli_dbgmsg(\"Machine type: ARM\\n\"); break; case 0x1c2: cli_dbgmsg(\"Machine type: THUMB\\n\"); break; case 0x1d3: cli_dbgmsg(\"Machine type: AM33\\n\"); break; case 0x520: cli_dbgmsg(\"Machine type: Infineon TriCore\\n\"); break; case 0xcef: cli_dbgmsg(\"Machine type: CEF\\n\"); break; case 0xebc: cli_dbgmsg(\"Machine type: EFI Byte Code\\n\"); break; case 0x9041: cli_dbgmsg(\"Machine type: M32R\\n\"); break; case 0xc0ee: cli_dbgmsg(\"Machine type: CEE\\n\"); break; case 0x8664: cli_dbgmsg(\"Machine type: AMD64\\n\"); break; default: cli_dbgmsg(\"Machine type: ** UNKNOWN ** (0x%x)\\n\", EC16(file_hdr.Machine)); } nsections = EC16(file_hdr.NumberOfSections); if(nsections < 1 || nsections > 96) { if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } if(!ctx->corrupted_input) { if(nsections) cli_warnmsg(\"PE file contains %d sections\\n\", nsections); else cli_warnmsg(\"PE file contains no sections\\n\"); } return CL_CLEAN; } cli_dbgmsg(\"NumberOfSections: %d\\n\", nsections); timestamp = (time_t) EC32(file_hdr.TimeDateStamp); cli_dbgmsg(\"TimeDateStamp: %s\", cli_ctime(×tamp, timestr, sizeof(timestr))); cli_dbgmsg(\"SizeOfOptionalHeader: %x\\n\", EC16(file_hdr.SizeOfOptionalHeader)); if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg(\"SizeOfOptionalHeader too small\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at = e_lfanew + sizeof(struct pe_image_file_hdr); if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg(\"Can't read optional file header\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_optional_hdr32); \/* This will be a chicken and egg problem until we drop 9x *\/ if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) { if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) { \/* FIXME: need to play around a bit more with xp64 *\/ cli_dbgmsg(\"Incorrect SizeOfOptionalHeader for PE32+\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } pe_plus = 1; } if(!pe_plus) { \/* PE *\/ if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) { \/* Seek to the end of the long header *\/ at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32); } if(DCONF & PE_CONF_UPACK) upack = (EC16(file_hdr.SizeOfOptionalHeader)==0x148); vep = EC32(optional_hdr32.AddressOfEntryPoint); hdr_size = EC32(optional_hdr32.SizeOfHeaders); cli_dbgmsg(\"File format: PE\\n\"); cli_dbgmsg(\"MajorLinkerVersion: %d\\n\", optional_hdr32.MajorLinkerVersion); cli_dbgmsg(\"MinorLinkerVersion: %d\\n\", optional_hdr32.MinorLinkerVersion); cli_dbgmsg(\"SizeOfCode: 0x%x\\n\", EC32(optional_hdr32.SizeOfCode)); cli_dbgmsg(\"SizeOfInitializedData: 0x%x\\n\", EC32(optional_hdr32.SizeOfInitializedData)); cli_dbgmsg(\"SizeOfUninitializedData: 0x%x\\n\", EC32(optional_hdr32.SizeOfUninitializedData)); cli_dbgmsg(\"AddressOfEntryPoint: 0x%x\\n\", vep); cli_dbgmsg(\"BaseOfCode: 0x%x\\n\", EC32(optional_hdr32.BaseOfCode)); cli_dbgmsg(\"SectionAlignment: 0x%x\\n\", EC32(optional_hdr32.SectionAlignment)); cli_dbgmsg(\"FileAlignment: 0x%x\\n\", EC32(optional_hdr32.FileAlignment)); cli_dbgmsg(\"MajorSubsystemVersion: %d\\n\", EC16(optional_hdr32.MajorSubsystemVersion)); cli_dbgmsg(\"MinorSubsystemVersion: %d\\n\", EC16(optional_hdr32.MinorSubsystemVersion)); cli_dbgmsg(\"SizeOfImage: 0x%x\\n\", EC32(optional_hdr32.SizeOfImage)); cli_dbgmsg(\"SizeOfHeaders: 0x%x\\n\", hdr_size); cli_dbgmsg(\"NumberOfRvaAndSizes: %d\\n\", EC32(optional_hdr32.NumberOfRvaAndSizes)); dirs = optional_hdr32.DataDirectory; } else { \/* PE+ *\/ \/* read the remaining part of the header *\/ if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg(\"Can't read optional file header\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32); vep = EC32(optional_hdr64.AddressOfEntryPoint); hdr_size = EC32(optional_hdr64.SizeOfHeaders); cli_dbgmsg(\"File format: PE32+\\n\"); cli_dbgmsg(\"MajorLinkerVersion: %d\\n\", optional_hdr64.MajorLinkerVersion); cli_dbgmsg(\"MinorLinkerVersion: %d\\n\", optional_hdr64.MinorLinkerVersion); cli_dbgmsg(\"SizeOfCode: 0x%x\\n\", EC32(optional_hdr64.SizeOfCode)); cli_dbgmsg(\"SizeOfInitializedData: 0x%x\\n\", EC32(optional_hdr64.SizeOfInitializedData)); cli_dbgmsg(\"SizeOfUninitializedData: 0x%x\\n\", EC32(optional_hdr64.SizeOfUninitializedData)); cli_dbgmsg(\"AddressOfEntryPoint: 0x%x\\n\", vep); cli_dbgmsg(\"BaseOfCode: 0x%x\\n\", EC32(optional_hdr64.BaseOfCode)); cli_dbgmsg(\"SectionAlignment: 0x%x\\n\", EC32(optional_hdr64.SectionAlignment)); cli_dbgmsg(\"FileAlignment: 0x%x\\n\", EC32(optional_hdr64.FileAlignment)); cli_dbgmsg(\"MajorSubsystemVersion: %d\\n\", EC16(optional_hdr64.MajorSubsystemVersion)); cli_dbgmsg(\"MinorSubsystemVersion: %d\\n\", EC16(optional_hdr64.MinorSubsystemVersion)); cli_dbgmsg(\"SizeOfImage: 0x%x\\n\", EC32(optional_hdr64.SizeOfImage)); cli_dbgmsg(\"SizeOfHeaders: 0x%x\\n\", hdr_size); cli_dbgmsg(\"NumberOfRvaAndSizes: %d\\n\", EC32(optional_hdr64.NumberOfRvaAndSizes)); dirs = optional_hdr64.DataDirectory; } switch(pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)) { case 0: cli_dbgmsg(\"Subsystem: Unknown\\n\"); break; case 1: cli_dbgmsg(\"Subsystem: Native (svc)\\n\"); native = 1; break; case 2: cli_dbgmsg(\"Subsystem: Win32 GUI\\n\"); break; case 3: cli_dbgmsg(\"Subsystem: Win32 console\\n\"); break; case 5: cli_dbgmsg(\"Subsystem: OS\/2 console\\n\"); break; case 7: cli_dbgmsg(\"Subsystem: POSIX console\\n\"); break; case 8: cli_dbgmsg(\"Subsystem: Native Win9x driver\\n\"); break; case 9: cli_dbgmsg(\"Subsystem: WinCE GUI\\n\"); break; case 10: cli_dbgmsg(\"Subsystem: EFI application\\n\"); break; case 11: cli_dbgmsg(\"Subsystem: EFI driver\\n\"); break; case 12: cli_dbgmsg(\"Subsystem: EFI runtime driver\\n\"); break; case 13: cli_dbgmsg(\"Subsystem: EFI ROM image\\n\"); break; case 14: cli_dbgmsg(\"Subsystem: Xbox\\n\"); break; case 16: cli_dbgmsg(\"Subsystem: Boot application\\n\"); break; default: cli_dbgmsg(\"Subsystem: ** UNKNOWN ** (0x%x)\\n\", pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)); } cli_dbgmsg(\"------------------------------------\\n\"); if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment)) || (pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment))%0x1000)) { cli_dbgmsg(\"Bad virtual alignment\\n\"); cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment)) || (pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment))%0x200)) { cli_dbgmsg(\"Bad file alignment\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); return CL_VIRUS; } fsize = map->len; section_hdr = (struct pe_image_section_hdr *) cli_calloc(nsections, sizeof(struct pe_image_section_hdr)); if(!section_hdr) { cli_dbgmsg(\"Can't allocate memory for section headers\\n\"); return CL_EMEM; } exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section)); if(!exe_sections) { cli_dbgmsg(\"Can't allocate memory for section headers\\n\"); free(section_hdr); return CL_EMEM; } valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment); falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment); if(fmap_readn(map, section_hdr, at, sizeof(struct pe_image_section_hdr)*nsections) != (int)(nsections*sizeof(struct pe_image_section_hdr))) { cli_dbgmsg(\"Can't read section header\\n\"); cli_dbgmsg(\"Possibly broken PE file\\n\"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_section_hdr)*nsections; for(i = 0; falign!=0x200 && iexe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz)) exe_sections[i].rsz = fsize - exe_sections[i].raw; cli_dbgmsg(\"Section %d\\n\", i); cli_dbgmsg(\"Section name: %s\\n\", sname); cli_dbgmsg(\"Section data (from headers - in memory)\\n\"); cli_dbgmsg(\"VirtualSize: 0x%x 0x%x\\n\", exe_sections[i].uvsz, exe_sections[i].vsz); cli_dbgmsg(\"VirtualAddress: 0x%x 0x%x\\n\", exe_sections[i].urva, exe_sections[i].rva); cli_dbgmsg(\"SizeOfRawData: 0x%x 0x%x\\n\", exe_sections[i].ursz, exe_sections[i].rsz); cli_dbgmsg(\"PointerToRawData: 0x%x 0x%x\\n\", exe_sections[i].uraw, exe_sections[i].raw); if(exe_sections[i].chr & 0x20) { cli_dbgmsg(\"Section contains executable code\\n\"); if(exe_sections[i].vsz < exe_sections[i].rsz) { cli_dbgmsg(\"Section contains free space\\n\"); \/* cli_dbgmsg(\"Dumping %d bytes\\n\", section_hdr.SizeOfRawData - section_hdr.VirtualSize); ddump(desc, section_hdr.PointerToRawData + section_hdr.VirtualSize, section_hdr.SizeOfRawData - section_hdr.VirtualSize, cli_gentemp(NULL)); *\/ } } if(exe_sections[i].chr & 0x20000000) cli_dbgmsg(\"Section's memory is executable\\n\"); if(exe_sections[i].chr & 0x80000000) cli_dbgmsg(\"Section's memory is writeable\\n\"); if (DETECT_BROKEN_PE && (!valign || (exe_sections[i].urva % valign))) { \/* Bad virtual alignment *\/ cli_dbgmsg(\"VirtualAddress is misaligned\\n\"); cli_dbgmsg(\"------------------------------------\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } if (exe_sections[i].rsz) { \/* Don't bother with virtual only sections *\/ if (exe_sections[i].raw >= fsize) { \/* really broken *\/ cli_dbgmsg(\"Broken PE file - Section %d starts beyond the end of file (Offset@ %lu, Total filesize %lu)\\n\", i, (unsigned long)exe_sections[i].raw, (unsigned long)fsize); cli_dbgmsg(\"------------------------------------\\n\"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; \/* no ninjas to see here! move along! *\/ } if(SCAN_ALGO && (DCONF & PE_CONF_POLIPOS) && !*sname && exe_sections[i].vsz > 40000 && exe_sections[i].vsz < 70000 && exe_sections[i].chr == 0xe0000060) polipos = i; \/* check MD5 section sigs *\/ md5_sect = ctx->engine->hm_mdb; if((DCONF & PE_CONF_MD5SECT) && md5_sect) { unsigned char md5_dig[16]; if(cli_hm_have_size(md5_sect, CLI_HASH_MD5, exe_sections[i].rsz) && cli_md5sect(map, &exe_sections[i], md5_dig) && cli_hm_scan(md5_dig, exe_sections[i].rsz, &virname, md5_sect, CLI_HASH_MD5) == CL_VIRUS) { cli_append_virus(ctx, virname); if(cli_hm_scan(md5_dig, fsize, NULL, ctx->engine->hm_fp, CLI_HASH_MD5) != CL_VIRUS) { if (!SCAN_ALL) { cli_dbgmsg(\"------------------------------------\\n\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } } viruses_found++; } } } cli_dbgmsg(\"------------------------------------\\n\"); if (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) { cli_dbgmsg(\"Found PE values with sign bit set\\n\"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } if(!i) { if (DETECT_BROKEN_PE && exe_sections[i].urva!=hdr_size) { \/* Bad first section RVA *\/ cli_dbgmsg(\"First section is in the wrong place\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } min = exe_sections[i].rva; max = exe_sections[i].rva + exe_sections[i].rsz; } else { if (DETECT_BROKEN_PE && exe_sections[i].urva - exe_sections[i-1].urva != exe_sections[i-1].vsz) { \/* No holes, no overlapping, no virtual disorder *\/ cli_dbgmsg(\"Virtually misplaced section (wrong order, overlapping, non contiguous)\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } if(exe_sections[i].rva < min) min = exe_sections[i].rva; if(exe_sections[i].rva + exe_sections[i].rsz > max) { max = exe_sections[i].rva + exe_sections[i].rsz; overlays = exe_sections[i].raw + exe_sections[i].rsz; } } } free(section_hdr); if(!(ep = cli_rawaddr(vep, exe_sections, nsections, &err, fsize, hdr_size)) && err) { cli_dbgmsg(\"EntryPoint out of file\\n\"); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } cli_dbgmsg(\"EntryPoint offset: 0x%x (%d)\\n\", ep, ep); if(pe_plus) { \/* Do not continue for PE32+ files *\/ free(exe_sections); return CL_CLEAN; } epsize = fmap_readn(map, epbuff, ep, 4096); \/* Disasm scan disabled since it's now handled by the bytecode *\/ \/* CLI_UNPTEMP(\"DISASM\",(exe_sections,0)); *\/ \/* if(disasmbuf((unsigned char*)epbuff, epsize, ndesc)) *\/ \/* ret = cli_scandesc(ndesc, ctx, CL_TYPE_PE_DISASM, 1, NULL, AC_SCAN_VIR); *\/ \/* close(ndesc); *\/ \/* CLI_TMPUNLK(); *\/ \/* free(tempfile); *\/ \/* if(ret == CL_VIRUS) { *\/ \/* free(exe_sections); *\/ \/* return ret; *\/ \/* } *\/ if(overlays) { int overlays_sz = fsize - overlays; if(overlays_sz > 0) { ret = cli_scanishield(ctx, overlays, overlays_sz); if(ret != CL_CLEAN) { free(exe_sections); return ret; } } } pedata.nsections = nsections; pedata.ep = ep; pedata.offset = 0; memcpy(&pedata.file_hdr, &file_hdr, sizeof(file_hdr)); memcpy(&pedata.opt32, &pe_opt.opt32, sizeof(pe_opt.opt32)); memcpy(&pedata.opt64, &pe_opt.opt64, sizeof(pe_opt.opt64)); memcpy(&pedata.dirs, dirs, sizeof(pedata.dirs)); pedata.e_lfanew = e_lfanew; pedata.overlays = overlays; pedata.overlays_sz = fsize - overlays; pedata.hdr_size = hdr_size; \/* Bytecode BC_PE_ALL hook *\/ bc_ctx = cli_bytecode_context_alloc(); if (!bc_ctx) { cli_errmsg(\"cli_scanpe: can't allocate memory for bc_ctx\\n\"); return CL_EMEM; } cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections); cli_bytecode_context_setctx(bc_ctx, ctx); ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_ALL, map); if (ret == CL_VIRUS || ret == CL_BREAK) { free(exe_sections); cli_bytecode_context_destroy(bc_ctx); return ret == CL_VIRUS ? CL_VIRUS : CL_CLEAN; } cli_bytecode_context_destroy(bc_ctx); \/* Attempt to detect some popular polymorphic viruses *\/ \/* W32.Parite.B *\/ if(SCAN_ALGO && (DCONF & PE_CONF_PARITE) && !dll && epsize == 4096 && ep == exe_sections[nsections - 1].raw) { const char *pt = cli_memstr(epbuff, 4040, \"\\x47\\x65\\x74\\x50\\x72\\x6f\\x63\\x41\\x64\\x64\\x72\\x65\\x73\\x73\\x00\", 15); if(pt) { pt += 15; if((((uint32_t)cli_readint32(pt) ^ (uint32_t)cli_readint32(pt + 4)) == 0x505a4f) && (((uint32_t)cli_readint32(pt + 8) ^ (uint32_t)cli_readint32(pt + 12)) == 0xffffb) && (((uint32_t)cli_readint32(pt + 16) ^ (uint32_t)cli_readint32(pt + 20)) == 0xb8)) { cli_append_virus(ctx,\"Heuristics.W32.Parite.B\"); if (!SCAN_ALL) { free(exe_sections); return CL_VIRUS; } viruses_found++; } } } \/* Kriz *\/ if(SCAN_ALGO && (DCONF & PE_CONF_KRIZ) && epsize >= 200 && CLI_ISCONTAINED(exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz, ep, 0x0fd2) && epbuff[1]=='\\x9c' && epbuff[2]=='\\x60') { enum {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSXORPRFX,KZSXOR,KZSDDELTA,KZSLOOP,KZSTOP}; uint8_t kzs[] = {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSTRASH,KZSXORPRFX,KZSXOR,KZSTRASH,KZSDDELTA,KZSTRASH,KZSLOOP,KZSTOP}; uint8_t *kzstate = kzs; uint8_t *kzcode = (uint8_t *)epbuff + 3; uint8_t kzdptr=0xff, kzdsize=0xff; int kzlen = 197, kzinitlen=0xffff, kzxorlen=-1; cli_dbgmsg(\"in kriz\\n\"); while(*kzstate!=KZSTOP) { uint8_t op; if(kzlen<=6) break; op = *kzcode++; kzlen--; switch (*kzstate) { case KZSTRASH: case KZSGETSIZE: { int opsz=0; switch(op) { case 0x81: kzcode+=5; kzlen-=5; break; case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbd: case 0xbe: case 0xbf: if(*kzstate==KZSGETSIZE && cli_readint32(kzcode)==0x0fd2) { kzinitlen = kzlen-5; kzdsize=op-0xb8; kzstate++; op=4; \/* fake the register to avoid breaking out *\/ cli_dbgmsg(\"kriz: using #%d as size counter\\n\", kzdsize); } opsz=4; case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4d: case 0x4e: case 0x4f: op&=7; if(op!=kzdptr && op!=kzdsize) { kzcode+=opsz; kzlen-=opsz; break; } default: kzcode--; kzlen++; kzstate++; } break; } case KZSCDELTA: if(op==0xe8 && (uint32_t)cli_readint32(kzcode) < 0xff) { kzlen-=*kzcode+4; kzcode+=*kzcode+4; kzstate++; } else *kzstate=KZSTOP; break; case KZSPDELTA: if((op&0xf8)==0x58 && (kzdptr=op-0x58)!=4) { kzstate++; cli_dbgmsg(\"kriz: using #%d as pointer\\n\", kzdptr); } else *kzstate=KZSTOP; break; case KZSXORPRFX: kzstate++; if(op==0x3e) break; case KZSXOR: if (op==0x80 && *kzcode==kzdptr+0xb0) { kzxorlen=kzlen; kzcode+=+6; kzlen-=+6; kzstate++; } else *kzstate=KZSTOP; break; case KZSDDELTA: if (op==kzdptr+0x48) kzstate++; else *kzstate=KZSTOP; break; case KZSLOOP: if (op==kzdsize+0x48 && *kzcode==0x75 && kzlen-(int8_t)kzcode[1]-3<=kzinitlen && kzlen-(int8_t)kzcode[1]>=kzxorlen) { cli_append_virus(ctx,\"Heuristics.W32.Kriz\"); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } cli_dbgmsg(\"kriz: loop out of bounds, corrupted sample?\\n\"); kzstate++; } } } \/* W32.Magistr.A\/B *\/ if(SCAN_ALGO && (DCONF & PE_CONF_MAGISTR) && !dll && (nsections>1) && (exe_sections[nsections - 1].chr & 0x80000000)) { uint32_t rsize, vsize, dam = 0; vsize = exe_sections[nsections - 1].uvsz; rsize = exe_sections[nsections - 1].rsz; if(rsize < exe_sections[nsections - 1].ursz) { rsize = exe_sections[nsections - 1].ursz; dam = 1; } if(vsize >= 0x612c && rsize >= 0x612c && ((vsize & 0xff) == 0xec)) { int bw = rsize < 0x7000 ? rsize : 0x7000; char *tbuff; if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) { if(cli_memstr(tbuff, 4091, \"\\xe8\\x2c\\x61\\x00\\x00\", 5)) { cli_append_virus(ctx, dam ? \"Heuristics.W32.Magistr.A.dam\" : \"Heuristics.W32.Magistr.A\"); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } } } else if(rsize >= 0x7000 && vsize >= 0x7000 && ((vsize & 0xff) == 0xed)) { int bw = rsize < 0x8000 ? rsize : 0x8000; char *tbuff; if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) { if(cli_memstr(tbuff, 4091, \"\\xe8\\x04\\x72\\x00\\x00\", 5)) { cli_append_virus(ctx,dam ? \"Heuristics.W32.Magistr.B.dam\" : \"Heuristics.W32.Magistr.B\"); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } } } } \/* W32.Polipos.A *\/ while(polipos && !dll && nsections > 2 && nsections < 13 && e_lfanew <= 0x800 && (EC16(optional_hdr32.Subsystem) == 2 || EC16(optional_hdr32.Subsystem) == 3) && EC16(file_hdr.Machine) == 0x14c && optional_hdr32.SizeOfStackReserve >= 0x80000) { uint32_t jump, jold, *jumps = NULL; uint8_t *code; unsigned int xsjs = 0; if(exe_sections[0].rsz > CLI_MAX_ALLOCATION) break; if(!exe_sections[0].rsz) break; if(!(code=fmap_need_off_once(map, exe_sections[0].raw, exe_sections[0].rsz))) break; for(i=0; i 1) continue; jump = cli_rawaddr(exe_sections[0].rva+i+5+cli_readint32(&code[i+1]), exe_sections, nsections, &err, fsize, hdr_size); if(err || !CLI_ISCONTAINED(exe_sections[polipos].raw, exe_sections[polipos].rsz, jump, 9)) continue; if(xsjs % 128 == 0) { if(xsjs == 1280) break; if(!(jumps=(uint32_t *)cli_realloc2(jumps, (xsjs+128)*sizeof(uint32_t)))) { free(exe_sections); return CL_EMEM; } } j=0; for(; j 1 && fsize > 64*1024 && fsize < 4*1024*1024) { if(dirs[2].Size) { struct swizz_stats *stats = cli_calloc(1, sizeof(*stats)); unsigned int m = 1000; ret = CL_CLEAN; if (!stats) ret = CL_EMEM; else { cli_parseres_special(EC32(dirs[2].VirtualAddress), EC32(dirs[2].VirtualAddress), map, exe_sections, nsections, fsize, hdr_size, 0, 0, &m, stats); if ((ret = cli_detect_swizz(stats)) == CL_VIRUS) { cli_append_virus(ctx,\"Heuristics.Trojan.Swizzor.Gen\"); } free(stats); } if (ret != CL_CLEAN) { if (!(ret == CL_VIRUS && SCAN_ALL)) { free(exe_sections); return ret; } viruses_found++; } } } \/* !!!!!!!!!!!!!! PACKERS START HERE !!!!!!!!!!!!!! *\/ corrupted_cur = ctx->corrupted_input; ctx->corrupted_input = 2; \/* caller will reset on return *\/ \/* UPX, FSG, MEW support *\/ \/* try to find the first section with physical size == 0 *\/ found = 0; if(DCONF & (PE_CONF_UPX | PE_CONF_FSG | PE_CONF_MEW)) { for(i = 0; i < (unsigned int) nsections - 1; i++) { if(!exe_sections[i].rsz && exe_sections[i].vsz && exe_sections[i + 1].rsz && exe_sections[i + 1].vsz) { found = 1; cli_dbgmsg(\"UPX\/FSG\/MEW: empty section found - assuming compression\\n\"); break; } } } \/* MEW support *\/ if (found && (DCONF & PE_CONF_MEW) && epsize>=16 && epbuff[0]=='\\xe9') { uint32_t fileoffset; char *tbuff; fileoffset = (vep + cli_readint32(epbuff + 1) + 5); while (fileoffset == 0x154 || fileoffset == 0x158) { uint32_t offdiff, uselzma; cli_dbgmsg (\"MEW: found MEW characteristics %08X + %08X + 5 = %08X\\n\", cli_readint32(epbuff + 1), vep, cli_readint32(epbuff + 1) + vep + 5); if(!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0))) break; if (fileoffset == 0x154) cli_dbgmsg(\"MEW: Win9x compatibility was set!\\n\"); else cli_dbgmsg(\"MEW: Win9x compatibility was NOT set!\\n\"); if((offdiff = cli_readint32(tbuff+1) - EC32(optional_hdr32.ImageBase)) <= exe_sections[i + 1].rva || offdiff >= exe_sections[i + 1].rva + exe_sections[i + 1].raw - 4) { cli_dbgmsg(\"MEW: ESI is not in proper section\\n\"); break; } offdiff -= exe_sections[i + 1].rva; if(!exe_sections[i + 1].rsz) { cli_dbgmsg(\"MEW: mew section is empty\\n\"); break; } ssize = exe_sections[i + 1].vsz; dsize = exe_sections[i].vsz; cli_dbgmsg(\"MEW: ssize %08x dsize %08x offdiff: %08x\\n\", ssize, dsize, offdiff); CLI_UNPSIZELIMITS(\"MEW\", MAX(ssize, dsize)); CLI_UNPSIZELIMITS(\"MEW\", MAX(ssize + dsize, exe_sections[i + 1].rsz)); if (exe_sections[i + 1].rsz < offdiff + 12 || exe_sections[i + 1].rsz > ssize) { cli_dbgmsg(\"MEW: Size mismatch: %08x\\n\", exe_sections[i + 1].rsz); break; } \/* allocate needed buffer *\/ if (!(src = cli_calloc (ssize + dsize, sizeof(char)))) { free(exe_sections); return CL_EMEM; } if((bytes = fmap_readn(map, src + dsize, exe_sections[i + 1].raw, exe_sections[i + 1].rsz)) != exe_sections[i + 1].rsz) { cli_dbgmsg(\"MEW: Can't read %d bytes [read: %lu]\\n\", exe_sections[i + 1].rsz, (unsigned long)bytes); free(exe_sections); free(src); return CL_EREAD; } cli_dbgmsg(\"MEW: %u (%08x) bytes read\\n\", (unsigned int)bytes, (unsigned int)bytes); \/* count offset to lzma proc, if lzma used, 0xe8 -> call *\/ if (tbuff[0x7b] == '\\xe8') { if (!CLI_ISCONTAINED(exe_sections[1].rva, exe_sections[1].vsz, cli_readint32(tbuff + 0x7c) + fileoffset + 0x80, 4)) { cli_dbgmsg(\"MEW: lzma proc out of bounds!\\n\"); free(src); break; \/* to next unpacker in chain *\/ } uselzma = cli_readint32(tbuff + 0x7c) - (exe_sections[0].rva - fileoffset - 0x80); } else { uselzma = 0; } CLI_UNPTEMP(\"MEW\",(src,exe_sections,0)); CLI_UNPRESULTS(\"MEW\",(unmew11(src, offdiff, ssize, dsize, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, uselzma, ndesc)),1,(src,0)); break; } } if(epsize<168) { free(exe_sections); return CL_CLEAN; } if (found || upack) { \/* Check EP for UPX vs. FSG vs. Upack *\/ \/* Upack 0.39 produces 2 types of executables * 3 sections: | 2 sections (one empty, I don't chech found if !upack, since it's in OR above): * mov esi, value | pusha * lodsd | call $+0x9 * push eax | * * Upack 1.1\/1.2 Beta produces [based on 2 samples (sUx) provided by aCaB]: * 2 sections * mov esi, value * loads * mov edi, eax * * Upack unknown [sample 0297729] * 3 sections * mov esi, value * push [esi] * jmp * *\/ \/* upack 0.39-3s + sample 0151477*\/ while(((upack && nsections == 3) && \/* 3 sections *\/ (( epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && \/* mov esi *\/ epbuff[5] == '\\xad' && epbuff[6] == '\\x50' \/* lodsd; push eax *\/ ) || \/* based on 0297729 sample from aCaB *\/ (epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && \/* mov esi *\/ epbuff[5] == '\\xff' && epbuff[6] == '\\x36' \/* push [esi] *\/ ) )) || ((!upack && nsections == 2) && \/* 2 sections *\/ (( \/* upack 0.39-2s *\/ epbuff[0] == '\\x60' && epbuff[1] == '\\xe8' && cli_readint32(epbuff+2) == 0x9 \/* pusha; call+9 *\/ ) || ( \/* upack 1.1\/1.2, based on 2 samples *\/ epbuff[0] == '\\xbe' && cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase) < min && \/* mov esi *\/ cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > 0 && epbuff[5] == '\\xad' && epbuff[6] == '\\x8b' && epbuff[7] == '\\xf8' \/* loads; mov edi, eax *\/ ) )) ) { uint32_t vma, off; int a,b,c; cli_dbgmsg(\"Upack characteristics found.\\n\"); a = exe_sections[0].vsz; b = exe_sections[1].vsz; if (upack) { cli_dbgmsg(\"Upack: var set\\n\"); c = exe_sections[2].vsz; ssize = exe_sections[0].ursz + exe_sections[0].uraw; off = exe_sections[0].rva; vma = EC32(optional_hdr32.ImageBase) + exe_sections[0].rva; } else { cli_dbgmsg(\"Upack: var NOT set\\n\"); c = exe_sections[1].rva; ssize = exe_sections[1].uraw; off = 0; vma = exe_sections[1].rva - exe_sections[1].uraw; } dsize = a+b+c; CLI_UNPSIZELIMITS(\"Upack\", MAX(MAX(dsize, ssize), exe_sections[1].ursz)); if (!CLI_ISCONTAINED(0, dsize, exe_sections[1].rva - off, exe_sections[1].ursz) || (upack && !CLI_ISCONTAINED(0, dsize, exe_sections[2].rva - exe_sections[0].rva, ssize)) || ssize > dsize) { cli_dbgmsg(\"Upack: probably malformed pe-header, skipping to next unpacker\\n\"); break; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); return CL_EMEM; } if(fmap_readn(map, dest, 0, ssize) != ssize) { cli_dbgmsg(\"Upack: Can't read raw data of section 0\\n\"); free(dest); break; } if(upack) memmove(dest + exe_sections[2].rva - exe_sections[0].rva, dest, ssize); if(fmap_readn(map, dest + exe_sections[1].rva - off, exe_sections[1].uraw, exe_sections[1].ursz) != exe_sections[1].ursz) { cli_dbgmsg(\"Upack: Can't read raw data of section 1\\n\"); free(dest); break; } CLI_UNPTEMP(\"Upack\",(dest,exe_sections,0)); CLI_UNPRESULTS(\"Upack\",(unupack(upack, dest, dsize, epbuff, vma, ep, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, ndesc)),1,(dest,0)); break; } } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\x87' && epbuff[1] == '\\x25') { \/* FSG v2.0 support - thanks to aCaB ! *\/ uint32_t newesi, newedi, newebx, newedx; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; CLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } newedx = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase); if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) { cli_dbgmsg(\"FSG: xchg out of bounds (%x), giving up\\n\", newedx); break; } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"Can't read raw data of section %d\\n\", i + 1); free(exe_sections); return CL_ESEEK; } dest = src + newedx - exe_sections[i + 1].rva; if(newedx < exe_sections[i + 1].rva || !CLI_ISCONTAINED(src, ssize, dest, 4)) { cli_dbgmsg(\"FSG: New ESP out of bounds\\n\"); break; } newedx = cli_readint32(dest) - EC32(optional_hdr32.ImageBase); if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) { cli_dbgmsg(\"FSG: New ESP (%x) is wrong\\n\", newedx); break; } dest = src + newedx - exe_sections[i + 1].rva; if(!CLI_ISCONTAINED(src, ssize, dest, 32)) { cli_dbgmsg(\"FSG: New stack out of bounds\\n\"); break; } newedi = cli_readint32(dest) - EC32(optional_hdr32.ImageBase); newesi = cli_readint32(dest + 4) - EC32(optional_hdr32.ImageBase); newebx = cli_readint32(dest + 16) - EC32(optional_hdr32.ImageBase); newedx = cli_readint32(dest + 20); if(newedi != exe_sections[i].rva) { cli_dbgmsg(\"FSG: Bad destination buffer (edi is %x should be %x)\\n\", newedi, exe_sections[i].rva); break; } if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) { cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\"); break; } if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newebx, 16)) { cli_dbgmsg(\"FSG: Array of functions out of bounds\\n\"); break; } newedx=cli_readint32(newebx + 12 - exe_sections[i + 1].rva + src) - EC32(optional_hdr32.ImageBase); cli_dbgmsg(\"FSG: found old EP @%x\\n\",newedx); if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(src); return CL_EMEM; } CLI_UNPTEMP(\"FSG\",(dest,exe_sections,0)); CLI_UNPRESULTSFSG2(\"FSG\",(unfsg_200(newesi - exe_sections[i + 1].rva + src, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, newedi, EC32(optional_hdr32.ImageBase), newedx, ndesc)),1,(dest,0)); break; } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min) { \/* FSG support - v. 1.33 (thx trog for the many samples) *\/ int sectcnt = 0; char *support; uint32_t newesi, newedi, oldep, gp, t; struct cli_exe_section *sections; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; CLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } if(!(t = cli_rawaddr(cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size)) && err ) { cli_dbgmsg(\"FSG: Support data out of padding area\\n\"); break; } gp = exe_sections[i + 1].raw - t; CLI_UNPSIZELIMITS(\"FSG\", gp); if(!(support = fmap_need_off_once(map, t, gp))) { cli_dbgmsg(\"Can't read %d bytes from padding area\\n\", gp); free(exe_sections); return CL_EREAD; } \/* newebx = cli_readint32(support) - EC32(optional_hdr32.ImageBase); Unused *\/ newedi = cli_readint32(support + 4) - EC32(optional_hdr32.ImageBase); \/* 1st dest *\/ newesi = cli_readint32(support + 8) - EC32(optional_hdr32.ImageBase); \/* Source *\/ if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) { cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\"); break; } if(newedi != exe_sections[i].rva) { cli_dbgmsg(\"FSG: Bad destination (is %x should be %x)\\n\", newedi, exe_sections[i].rva); break; } \/* Counting original sections *\/ for(t = 12; t < gp - 4; t += 4) { uint32_t rva = cli_readint32(support+t); if(!rva) break; rva -= EC32(optional_hdr32.ImageBase)+1; sectcnt++; if(rva % 0x1000) cli_dbgmsg(\"FSG: Original section %d is misaligned\\n\", sectcnt); if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) { cli_dbgmsg(\"FSG: Original section %d is out of bounds\\n\", sectcnt); break; } } if(t >= gp - 4 || cli_readint32(support + t)) { break; } if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { free(exe_sections); return CL_EMEM; } sections[0].rva = newedi; for(t = 1; t <= (uint32_t)sectcnt; t++) sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(optional_hdr32.ImageBase); if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"Can't read raw data of section %d\\n\", i); free(exe_sections); free(sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(sections); return CL_EMEM; } oldep = vep + 161 + 6 + cli_readint32(epbuff+163); cli_dbgmsg(\"FSG: found old EP @%x\\n\", oldep); CLI_UNPTEMP(\"FSG\",(dest,sections,exe_sections,0)); CLI_UNPRESULTSFSG1(\"FSG\",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0)); break; \/* were done with 1.33 *\/ } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\xbb' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min && epbuff[5] == '\\xbf' && epbuff[10] == '\\xbe' && vep >= exe_sections[i + 1].rva && vep - exe_sections[i + 1].rva > exe_sections[i + 1].rva - 0xe0 ) { \/* FSG support - v. 1.31 *\/ int sectcnt = 0; uint32_t gp, t = cli_rawaddr(cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size); char *support; uint32_t newesi = cli_readint32(epbuff+11) - EC32(optional_hdr32.ImageBase); uint32_t newedi = cli_readint32(epbuff+6) - EC32(optional_hdr32.ImageBase); uint32_t oldep = vep - exe_sections[i + 1].rva; struct cli_exe_section *sections; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; if(err) { cli_dbgmsg(\"FSG: Support data out of padding area\\n\"); break; } if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].raw) { cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\"); break; } if(newedi != exe_sections[i].rva) { cli_dbgmsg(\"FSG: Bad destination (is %x should be %x)\\n\", newedi, exe_sections[i].rva); break; } CLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } gp = exe_sections[i + 1].raw - t; CLI_UNPSIZELIMITS(\"FSG\", gp) if(!(support = fmap_need_off_once(map, t, gp))) { cli_dbgmsg(\"Can't read %d bytes from padding area\\n\", gp); free(exe_sections); return CL_EREAD; } \/* Counting original sections *\/ for(t = 0; t < gp - 2; t += 2) { uint32_t rva = support[t]|(support[t+1]<<8); if (rva == 2 || rva == 1) break; rva = ((rva-2)<<12) - EC32(optional_hdr32.ImageBase); sectcnt++; if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) { cli_dbgmsg(\"FSG: Original section %d is out of bounds\\n\", sectcnt); break; } } if(t >= gp-10 || cli_readint32(support + t + 6) != 2) { break; } if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { free(exe_sections); return CL_EMEM; } sections[0].rva = newedi; for(t = 0; t <= (uint32_t)sectcnt - 1; t++) { sections[t+1].rva = (((support[t*2]|(support[t*2+1]<<8))-2)<<12)-EC32(optional_hdr32.ImageBase); } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"FSG: Can't read raw data of section %d\\n\", i); free(exe_sections); free(sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(sections); return CL_EMEM; } gp = 0xda + 6*(epbuff[16]=='\\xe8'); oldep = vep + gp + 6 + cli_readint32(src+gp+2+oldep); cli_dbgmsg(\"FSG: found old EP @%x\\n\", oldep); CLI_UNPTEMP(\"FSG\",(dest,sections,exe_sections,0)); CLI_UNPRESULTSFSG1(\"FSG\",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0)); break; \/* were done with 1.31 *\/ } if(found && (DCONF & PE_CONF_UPX)) { \/* UPX support *\/ \/* we assume (i + 1) is UPX1 *\/ ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz + exe_sections[i + 1].vsz; CLI_UNPSIZELIMITS(\"UPX\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize || dsize > CLI_MAX_ALLOCATION ) { cli_dbgmsg(\"UPX: Size mismatch or dsize too big (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"UPX: Can't read raw data of section %d\\n\", i+1); free(exe_sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize + 8192, sizeof(char))) == NULL) { free(exe_sections); return CL_EMEM; } \/* try to detect UPX code *\/ if(cli_memstr(UPX_NRV2B, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2B, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg(\"UPX: Looks like a NRV2B decompression routine\\n\"); upxfn = upx_inflate2b; } else if(cli_memstr(UPX_NRV2D, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2D, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg(\"UPX: Looks like a NRV2D decompression routine\\n\"); upxfn = upx_inflate2d; } else if(cli_memstr(UPX_NRV2E, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2E, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg(\"UPX: Looks like a NRV2E decompression routine\\n\"); upxfn = upx_inflate2e; } if(upxfn) { int skew = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase) - exe_sections[i + 1].rva; if(epbuff[1] != '\\xbe' || skew <= 0 || skew > 0xfff) { \/* FIXME: legit skews?? *\/ skew = 0; } else if(skew > ssize) { \/* Ignore suggested skew larger than section size *\/ cli_dbgmsg(\"UPX: Ignoring bad skew of %d bytes\\n\", skew); skew = 0; } else { cli_dbgmsg(\"UPX: UPX1 seems skewed by %d bytes\\n\", skew); } if(upxfn(src + skew, ssize - skew, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep-skew) >= 0 || upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0) { upx_success = 1; } else if(skew && (upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)) { upx_success = 1; } if(upx_success) cli_dbgmsg(\"UPX: Successfully decompressed\\n\"); else cli_dbgmsg(\"UPX: Preferred decompressor failed\\n\"); } if(!upx_success && upxfn != upx_inflate2b) { if(upx_inflate2b(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2b(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg(\"UPX: NRV2B decompressor failed\\n\"); } else { upx_success = 1; cli_dbgmsg(\"UPX: Successfully decompressed with NRV2B\\n\"); } } if(!upx_success && upxfn != upx_inflate2d) { if(upx_inflate2d(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2d(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg(\"UPX: NRV2D decompressor failed\\n\"); } else { upx_success = 1; cli_dbgmsg(\"UPX: Successfully decompressed with NRV2D\\n\"); } } if(!upx_success && upxfn != upx_inflate2e) { if(upx_inflate2e(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2e(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg(\"UPX: NRV2E decompressor failed\\n\"); } else { upx_success = 1; cli_dbgmsg(\"UPX: Successfully decompressed with NRV2E\\n\"); } } if(cli_memstr(UPX_LZMA2, 20, epbuff + 0x2f, 20)) { uint32_t strictdsize=cli_readint32(epbuff+0x21), skew = 0; if(ssize > 0x15 && epbuff[0] == '\\x60' && epbuff[1] == '\\xbe') { skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase; if(skew!=0x15) skew = 0; } if(strictdsize<=dsize) upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0; } else if (cli_memstr(UPX_LZMA1, 20, epbuff + 0x39, 20)) { uint32_t strictdsize=cli_readint32(epbuff+0x2b), skew = 0; if(ssize > 0x15 && epbuff[0] == '\\x60' && epbuff[1] == '\\xbe') { skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase; if(skew!=0x15) skew = 0; } if(strictdsize<=dsize) upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0; } if(!upx_success) { cli_dbgmsg(\"UPX: All decompressors failed\\n\"); free(dest); } } if(upx_success) { free(exe_sections); CLI_UNPTEMP(\"UPX\/FSG\",(dest,0)); if((unsigned int) write(ndesc, dest, dsize) != dsize) { cli_dbgmsg(\"UPX\/FSG: Can't write %d bytes\\n\", dsize); free(tempfile); free(dest); close(ndesc); return CL_EWRITE; } free(dest); lseek(ndesc, 0, SEEK_SET); if(ctx->engine->keeptmp) cli_dbgmsg(\"UPX\/FSG: Decompressed data saved in %s\\n\", tempfile); cli_dbgmsg(\"***** Scanning decompressed file *****\\n\"); SHA_OFF; if((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS) { close(ndesc); CLI_TMPUNLK(); free(tempfile); SHA_RESET; return CL_VIRUS; } SHA_RESET; close(ndesc); CLI_TMPUNLK(); free(tempfile); return ret; } \/* Petite *\/ if(epsize<200) { free(exe_sections); return CL_CLEAN; } found = 2; if(epbuff[0] != '\\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 1].rva + EC32(optional_hdr32.ImageBase)) { if(nsections < 2 || epbuff[0] != '\\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 2].rva + EC32(optional_hdr32.ImageBase)) found = 0; else found = 1; } if(found && (DCONF & PE_CONF_PETITE)) { cli_dbgmsg(\"Petite: v2.%d compression detected\\n\", found); if(cli_readint32(epbuff + 0x80) == 0x163c988d) { cli_dbgmsg(\"Petite: level zero compression is not supported yet\\n\"); } else { dsize = max - min; CLI_UNPSIZELIMITS(\"Petite\", dsize); if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { cli_dbgmsg(\"Petite: Can't allocate %d bytes\\n\", dsize); free(exe_sections); return CL_EMEM; } for(i = 0 ; i < nsections; i++) { if(exe_sections[i].raw) { if(!exe_sections[i].rsz || fmap_readn(map, dest + exe_sections[i].rva - min, exe_sections[i].raw, exe_sections[i].ursz) != exe_sections[i].ursz) { free(exe_sections); free(dest); return CL_CLEAN; } } } CLI_UNPTEMP(\"Petite\",(dest,exe_sections,0)); CLI_UNPRESULTS(\"Petite\",(petite_inflate2x_1to9(dest, min, max - min, exe_sections, nsections - (found == 1 ? 1 : 0), EC32(optional_hdr32.ImageBase),vep, ndesc, found, EC32(optional_hdr32.DataDirectory[2].VirtualAddress),EC32(optional_hdr32.DataDirectory[2].Size))),0,(dest,0)); } } \/* PESpin 1.1 *\/ if((DCONF & PE_CONF_PESPIN) && nsections > 1 && vep >= exe_sections[nsections - 1].rva && vep < exe_sections[nsections - 1].rva + exe_sections[nsections - 1].rsz - 0x3217 - 4 && memcmp(epbuff+4, \"\\xe8\\x00\\x00\\x00\\x00\\x8b\\x1c\\x24\\x83\\xc3\", 10) == 0) { char *spinned; CLI_UNPSIZELIMITS(\"PEspin\", fsize); if((spinned = (char *) cli_malloc(fsize)) == NULL) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) { cli_dbgmsg(\"PESpin: Can't read %lu bytes\\n\", (unsigned long)fsize); free(spinned); free(exe_sections); return CL_EREAD; } CLI_UNPTEMP(\"PESpin\",(spinned,exe_sections,0)); CLI_UNPRESULTS_(\"PEspin\",SPINCASE(),(unspin(spinned, fsize, exe_sections, nsections - 1, vep, ndesc, ctx)),0,(spinned,0)); } \/* yC 1.3 & variants *\/ if((DCONF & PE_CONF_YC) && nsections > 1 && (EC32(optional_hdr32.AddressOfEntryPoint) == exe_sections[nsections - 1].rva + 0x60)) { uint32_t ecx = 0; int16_t offset; \/* yC 1.3 *\/ if (!memcmp(epbuff, \"\\x55\\x8B\\xEC\\x53\\x56\\x57\\x60\\xE8\\x00\\x00\\x00\\x00\\x5D\\x81\\xED\", 15) && !memcmp(epbuff+0x26, \"\\x8D\\x3A\\x8B\\xF7\\x33\\xC0\\xEB\\x04\\x90\\xEB\\x01\\xC2\\xAC\", 13) && ((uint8_t)epbuff[0x13] == 0xB9) && ((uint16_t)(cli_readint16(epbuff+0x18)) == 0xE981) && !memcmp(epbuff+0x1e,\"\\x8B\\xD5\\x81\\xC2\", 4)) { offset = 0; if (0x6c - cli_readint32(epbuff+0xf) + cli_readint32(epbuff+0x22) == 0xC6) ecx = cli_readint32(epbuff+0x14) - cli_readint32(epbuff+0x1a); } \/* yC 1.3 variant *\/ if (!ecx && !memcmp(epbuff, \"\\x55\\x8B\\xEC\\x83\\xEC\\x40\\x53\\x56\\x57\", 9) && !memcmp(epbuff+0x17, \"\\xe8\\x00\\x00\\x00\\x00\\x5d\\x81\\xed\", 8) && ((uint8_t)epbuff[0x23] == 0xB9)) { offset = 0x10; if (0x6c - cli_readint32(epbuff+0x1f) + cli_readint32(epbuff+0x32) == 0xC6) ecx = cli_readint32(epbuff+0x24) - cli_readint32(epbuff+0x2a); } \/* yC 1.x\/modified *\/ if (!ecx && !memcmp(epbuff, \"\\x60\\xe8\\x00\\x00\\x00\\x00\\x5d\\x81\\xed\",9) && ((uint8_t)epbuff[0xd] == 0xb9) && ((uint16_t)cli_readint16(epbuff + 0x12)== 0xbd8d) && !memcmp(epbuff+0x18, \"\\x8b\\xf7\\xac\", 3)) { offset = -0x18; if (0x66 - cli_readint32(epbuff+0x9) + cli_readint32(epbuff+0x14) == 0xae) ecx = cli_readint32(epbuff+0xe); } if (ecx > 0x800 && ecx < 0x2000 && !memcmp(epbuff+0x63+offset, \"\\xaa\\xe2\\xcc\", 3) && (fsize >= exe_sections[nsections-1].raw + 0xC6 + ecx + offset)) { char *spinned; if((spinned = (char *) cli_malloc(fsize)) == NULL) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) { cli_dbgmsg(\"yC: Can't read %lu bytes\\n\", (unsigned long)fsize); free(spinned); free(exe_sections); return CL_EREAD; } cli_dbgmsg(\"%d,%d,%d,%d\\n\", nsections-1, e_lfanew, ecx, offset); CLI_UNPTEMP(\"yC\",(spinned,exe_sections,0)); CLI_UNPRESULTS(\"yC\",(yc_decrypt(spinned, fsize, exe_sections, nsections-1, e_lfanew, ndesc, ecx, offset)),0,(spinned,0)); } } \/* WWPack *\/ while ((DCONF & PE_CONF_WWPACK) && nsections > 1 && vep == exe_sections[nsections - 1].rva && memcmp(epbuff, \"\\x53\\x55\\x8b\\xe8\\x33\\xdb\\xeb\", 7) == 0 && memcmp(epbuff+0x68, \"\\xe8\\x00\\x00\\x00\\x00\\x58\\x2d\\x6d\\x00\\x00\\x00\\x50\\x60\\x33\\xc9\\x50\\x58\\x50\\x50\", 19) == 0) { uint32_t head = exe_sections[nsections - 1].raw; uint8_t *packer; ssize = 0; for(i=0 ; ; i++) { if(exe_sections[i].rawssize) break; CLI_UNPSIZELIMITS(\"WWPack\", ssize); if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, src, 0, head) != head) { cli_dbgmsg(\"WWPack: Can't read %d bytes from headers\\n\", head); free(src); free(exe_sections); return CL_EREAD; } for(i = 0 ; i < (unsigned int)nsections-1; i++) { if(!exe_sections[i].rsz) continue; if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break; if(fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break; } if(i+1!=nsections) { cli_dbgmsg(\"WWpack: Probably hacked\/damaged file.\\n\"); free(src); break; } if((packer = (uint8_t *) cli_calloc(exe_sections[nsections - 1].rsz, sizeof(char))) == NULL) { free(src); free(exe_sections); return CL_EMEM; } if(!exe_sections[nsections - 1].rsz || (size_t) fmap_readn(map, packer, exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz) != exe_sections[nsections - 1].rsz) { cli_dbgmsg(\"WWPack: Can't read %d bytes from wwpack sect\\n\", exe_sections[nsections - 1].rsz); free(src); free(packer); free(exe_sections); return CL_EREAD; } CLI_UNPTEMP(\"WWPack\",(src,packer,exe_sections,0)); CLI_UNPRESULTS(\"WWPack\",(wwunpack((uint8_t *)src, ssize, packer, exe_sections, nsections-1, e_lfanew, ndesc)),0,(src,packer,0)); break; } \/* ASPACK support *\/ while((DCONF & PE_CONF_ASPACK) && ep+58+0x70e < fsize && !memcmp(epbuff,\"\\x60\\xe8\\x03\\x00\\x00\\x00\\xe9\\xeb\",8)) { if(epsize<0x3bf || memcmp(epbuff+0x3b9, \"\\x68\\x00\\x00\\x00\\x00\\xc3\",6)) break; ssize = 0; for(i=0 ; i< nsections ; i++) if(ssizecorrupted_input = corrupted_cur; \/* Bytecode BC_PE_UNPACKER hook *\/ bc_ctx = cli_bytecode_context_alloc(); if (!bc_ctx) { cli_errmsg(\"cli_scanpe: can't allocate memory for bc_ctx\\n\"); return CL_EMEM; } cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections); cli_bytecode_context_setctx(bc_ctx, ctx); ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_UNPACKER, map); switch (ret) { case CL_VIRUS: free(exe_sections); cli_bytecode_context_destroy(bc_ctx); return CL_VIRUS; case CL_SUCCESS: ndesc = cli_bytecode_context_getresult_file(bc_ctx, &tempfile); cli_bytecode_context_destroy(bc_ctx); if (ndesc != -1 && tempfile) { CLI_UNPRESULTS(\"bytecode PE hook\", 1, 1, (0)); } break; default: cli_bytecode_context_destroy(bc_ctx); } free(exe_sections); if (SCAN_ALL && viruses_found) return CL_VIRUS; return CL_CLEAN;","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":363557,"input":"deliver_message(uschar *id, BOOL forced, BOOL give_up) { int i, rc; int final_yield = DELIVER_ATTEMPTED_NORMAL; time_t now = time(NULL); address_item *addr_last = NULL; uschar *filter_message = NULL; int process_recipients = RECIP_ACCEPT; open_db dbblock; open_db *dbm_file; extern int acl_where; uschar *info = queue_run_pid == (pid_t)0 ? string_sprintf(\"delivering %s\", id) : string_sprintf(\"delivering %s (queue run pid %d)\", id, queue_run_pid); \/* If the D_process_info bit is on, set_process_info() will output debugging information. If not, we want to show this initial information if D_deliver or D_queue_run is set or in verbose mode. *\/ set_process_info(\"%s\", info); if ( !(debug_selector & D_process_info) && (debug_selector & (D_deliver|D_queue_run|D_v)) ) debug_printf(\"%s\\n\", info); \/* Ensure that we catch any subprocesses that are created. Although Exim sets SIG_DFL as its initial default, some routes through the code end up here with it set to SIG_IGN - cases where a non-synchronous delivery process has been forked, but no re-exec has been done. We use sigaction rather than plain signal() on those OS where SA_NOCLDWAIT exists, because we want to be sure it is turned off. (There was a problem on AIX with this.) *\/ #ifdef SA_NOCLDWAIT { struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(SIGCHLD, &act, NULL); } #else signal(SIGCHLD, SIG_DFL); #endif \/* Make the forcing flag available for routers and transports, set up the global message id field, and initialize the count for returned files and the message size. This use of strcpy() is OK because the length id is checked when it is obtained from a command line (the -M or -q options), and otherwise it is known to be a valid message id. *\/ if (id != message_id) Ustrcpy(message_id, id); f.deliver_force = forced; return_count = 0; message_size = 0; \/* Initialize some flags *\/ update_spool = FALSE; remove_journal = TRUE; \/* Set a known context for any ACLs we call via expansions *\/ acl_where = ACL_WHERE_DELIVERY; \/* Reset the random number generator, so that if several delivery processes are started from a queue runner that has already used random numbers (for sorting), they don't all get the same sequence. *\/ random_seed = 0; \/* Open and lock the message's data file. Exim locks on this one because the header file may get replaced as it is re-written during the delivery process. Any failures cause messages to be written to the log, except for missing files while queue running - another process probably completed delivery. As part of opening the data file, message_subdir gets set. *\/ if ((deliver_datafile = spool_open_datafile(id)) < 0) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ \/* The value of message_size at this point has been set to the data length, plus one for the blank line that notionally precedes the data. *\/ \/* Now read the contents of the header file, which will set up the headers in store, and also the list of recipients and the tree of non-recipients and assorted flags. It updates message_size. If there is a reading or format error, give up; if the message has been around for sufficiently long, remove it. *\/ { uschar * spoolname = string_sprintf(\"%s-H\", id); if ((rc = spool_read_header(spoolname, TRUE, TRUE)) != spool_read_OK) { if (errno == ERRNO_SPOOLFORMAT) { struct stat statbuf; if (Ustat(spool_fname(US\"input\", message_subdir, spoolname, US\"\"), &statbuf) == 0) log_write(0, LOG_MAIN, \"Format error in spool file %s: \" \"size=\" OFF_T_FMT, spoolname, statbuf.st_size); else log_write(0, LOG_MAIN, \"Format error in spool file %s\", spoolname); } else log_write(0, LOG_MAIN, \"Error reading spool file %s: %s\", spoolname, strerror(errno)); \/* If we managed to read the envelope data, received_time contains the time the message was received. Otherwise, we can calculate it from the message id. *\/ if (rc != spool_read_hdrerror) { received_time.tv_sec = received_time.tv_usec = 0; \/*XXX subsec precision?*\/ for (i = 0; i < 6; i++) received_time.tv_sec = received_time.tv_sec * BASE_62 + tab62[id[i] - '0']; } \/* If we've had this malformed message too long, sling it. *\/ if (now - received_time.tv_sec > keep_malformed) { Uunlink(spool_fname(US\"msglog\", message_subdir, id, US\"\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-H\")); Uunlink(spool_fname(US\"input\", message_subdir, id, US\"-J\")); log_write(0, LOG_MAIN, \"Message removed because older than %s\", readconf_printtime(keep_malformed)); } (void)close(deliver_datafile); deliver_datafile = -1; return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* The spool header file has been read. Look to see if there is an existing journal file for this message. If there is, it means that a previous delivery attempt crashed (program or host) before it could update the spool header file. Read the list of delivered addresses from the journal and add them to the nonrecipients tree. Then update the spool file. We can leave the journal in existence, as it will get further successful deliveries added to it in this run, and it will be deleted if this function gets to its end successfully. Otherwise it might be needed again. *\/ { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); FILE * jread; if ( (journal_fd = Uopen(fname, O_RDWR|O_APPEND #ifdef O_CLOEXEC | O_CLOEXEC #endif #ifdef O_NOFOLLOW | O_NOFOLLOW #endif , SPOOL_MODE)) >= 0 && lseek(journal_fd, 0, SEEK_SET) == 0 && (jread = fdopen(journal_fd, \"rb\")) ) { while (Ufgets(big_buffer, big_buffer_size, jread)) { int n = Ustrlen(big_buffer); big_buffer[n-1] = 0; tree_add_nonrecipient(big_buffer); DEBUG(D_deliver) debug_printf(\"Previously delivered address %s taken from \" \"journal file\\n\", big_buffer); } rewind(jread); if ((journal_fd = dup(fileno(jread))) < 0) journal_fd = fileno(jread); else (void) fclose(jread); \/* Try to not leak the FILE resource *\/ \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } else if (errno != ENOENT) { log_write(0, LOG_MAIN|LOG_PANIC, \"attempt to open journal for reading gave: \" \"%s\", strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* A null recipients list indicates some kind of disaster. *\/ if (!recipients_list) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN, \"Spool error: no recipients for %s\", fname); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* Handle a message that is frozen. There are a number of different things that can happen, but in the default situation, unless forced, no delivery is attempted. *\/ if (f.deliver_freeze) { #ifdef SUPPORT_MOVE_FROZEN_MESSAGES \/* Moving to another directory removes the message from Exim's view. Other tools must be used to deal with it. Logging of this action happens in spool_move_message() and its subfunctions. *\/ if ( move_frozen_messages && spool_move_message(id, message_subdir, US\"\", US\"F\") ) return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ #endif \/* For all frozen messages (bounces or not), timeout_frozen_after sets the maximum time to keep messages that are frozen. Thaw if we reach it, with a flag causing all recipients to be failed. The time is the age of the message, not the time since freezing. *\/ if (timeout_frozen_after > 0 && message_age >= timeout_frozen_after) { log_write(0, LOG_MAIN, \"cancelled by timeout_frozen_after\"); process_recipients = RECIP_FAIL_TIMEOUT; } \/* For bounce messages (and others with no sender), thaw if the error message ignore timer is exceeded. The message will be discarded if this delivery fails. *\/ else if (!*sender_address && message_age >= ignore_bounce_errors_after) log_write(0, LOG_MAIN, \"Unfrozen by errmsg timer\"); \/* If this is a bounce message, or there's no auto thaw, or we haven't reached the auto thaw time yet, and this delivery is not forced by an admin user, do not attempt delivery of this message. Note that forced is set for continuing messages down the same channel, in order to skip load checking and ignore hold domains, but we don't want unfreezing in that case. *\/ else { if ( ( sender_address[0] == 0 || auto_thaw <= 0 || now <= deliver_frozen_at + auto_thaw ) && ( !forced || !f.deliver_force_thaw || !f.admin_user || continue_hostname ) ) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(L_skip_delivery, LOG_MAIN, \"Message is frozen\"); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* If delivery was forced (by an admin user), assume a manual thaw. Otherwise it's an auto thaw. *\/ if (forced) { f.deliver_manual_thaw = TRUE; log_write(0, LOG_MAIN, \"Unfrozen by forced delivery\"); } else log_write(0, LOG_MAIN, \"Unfrozen by auto-thaw\"); } \/* We get here if any of the rules for unfreezing have triggered. *\/ f.deliver_freeze = FALSE; update_spool = TRUE; } \/* Open the message log file if we are using them. This records details of deliveries, deferments, and failures for the benefit of the mail administrator. The log is not used by exim itself to track the progress of a message; that is done by rewriting the header spool file. *\/ if (message_logs) { uschar * fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); uschar * error; int fd; if ((fd = open_msglog_file(fname, SPOOL_MODE, &error)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't %s message log %s: %s\", error, fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Make a C stream out of it. *\/ if (!(message_log = fdopen(fd, \"a\"))) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't fdopen message log %s: %s\", fname, strerror(errno)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } } \/* If asked to give up on a message, log who did it, and set the action for all the addresses. *\/ if (give_up) { struct passwd *pw = getpwuid(real_uid); log_write(0, LOG_MAIN, \"cancelled by %s\", pw ? US pw->pw_name : string_sprintf(\"uid %ld\", (long int)real_uid)); process_recipients = RECIP_FAIL; } \/* Otherwise, if there are too many Received: headers, fail all recipients. *\/ else if (received_count > received_headers_max) process_recipients = RECIP_FAIL_LOOP; \/* Otherwise, if a system-wide, address-independent message filter is specified, run it now, except in the case when we are failing all recipients as a result of timeout_frozen_after. If the system filter yields \"delivered\", then ignore the true recipients of the message. Failure of the filter file is logged, and the delivery attempt fails. *\/ else if (system_filter && process_recipients != RECIP_FAIL_TIMEOUT) { int rc; int filtertype; ugid_block ugid; redirect_block redirect; if (system_filter_uid_set) { ugid.uid = system_filter_uid; ugid.gid = system_filter_gid; ugid.uid_set = ugid.gid_set = TRUE; } else { ugid.uid_set = ugid.gid_set = FALSE; } return_path = sender_address; f.enable_dollar_recipients = TRUE; \/* Permit $recipients in system filter *\/ f.system_filtering = TRUE; \/* Any error in the filter file causes a delivery to be abandoned. *\/ redirect.string = system_filter; redirect.isfile = TRUE; redirect.check_owner = redirect.check_group = FALSE; redirect.owners = NULL; redirect.owngroups = NULL; redirect.pw = NULL; redirect.modemask = 0; DEBUG(D_deliver|D_filter) debug_printf(\"running system filter\\n\"); rc = rda_interpret( &redirect, \/* Where the data is *\/ RDO_DEFER | \/* Turn on all the enabling options *\/ RDO_FAIL | \/* Leave off all the disabling options *\/ RDO_FILTER | RDO_FREEZE | RDO_REALLOG | RDO_REWRITE, NULL, \/* No :include: restriction (not used in filter) *\/ NULL, \/* No sieve vacation directory (not sieve!) *\/ NULL, \/* No sieve enotify mailto owner (not sieve!) *\/ NULL, \/* No sieve user address (not sieve!) *\/ NULL, \/* No sieve subaddress (not sieve!) *\/ &ugid, \/* uid\/gid data *\/ &addr_new, \/* Where to hang generated addresses *\/ &filter_message, \/* Where to put error message *\/ NULL, \/* Don't skip syntax errors *\/ &filtertype, \/* Will always be set to FILTER_EXIM for this call *\/ US\"system filter\"); \/* For error messages *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter returned %d\\n\", rc); if (rc == FF_ERROR || rc == FF_NONEXIST) { (void)close(deliver_datafile); deliver_datafile = -1; log_write(0, LOG_MAIN|LOG_PANIC, \"Error in system filter: %s\", string_printing(filter_message)); return continue_closedown(); \/* yields DELIVER_NOT_ATTEMPTED *\/ } \/* Reset things. If the filter message is an empty string, which can happen for a filter \"fail\" or \"freeze\" command with no text, reset it to NULL. *\/ f.system_filtering = FALSE; f.enable_dollar_recipients = FALSE; if (filter_message && filter_message[0] == 0) filter_message = NULL; \/* Save the values of the system filter variables so that user filters can use them. *\/ memcpy(filter_sn, filter_n, sizeof(filter_sn)); \/* The filter can request that delivery of the original addresses be deferred. *\/ if (rc == FF_DEFER) { process_recipients = RECIP_DEFER; deliver_msglog(\"Delivery deferred by system filter\\n\"); log_write(0, LOG_MAIN, \"Delivery deferred by system filter\"); } \/* The filter can request that a message be frozen, but this does not take place if the message has been manually thawed. In that case, we must unset \"delivered\", which is forced by the \"freeze\" command to make -bF work properly. *\/ else if (rc == FF_FREEZE && !f.deliver_manual_thaw) { f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); process_recipients = RECIP_DEFER; frozen_info = string_sprintf(\" by the system filter%s%s\", filter_message ? US\": \" : US\"\", filter_message ? filter_message : US\"\"); } \/* The filter can request that a message be failed. The error message may be quite long - it is sent back to the sender in the bounce - but we don't want to fill up the log with repetitions of it. If it starts with << then the text between << and >> is written to the log, with the rest left for the bounce message. *\/ else if (rc == FF_FAIL) { uschar *colon = US\"\"; uschar *logmsg = US\"\"; int loglen = 0; process_recipients = RECIP_FAIL_FILTER; if (filter_message) { uschar *logend; colon = US\": \"; if ( filter_message[0] == '<' && filter_message[1] == '<' && (logend = Ustrstr(filter_message, \">>\")) ) { logmsg = filter_message + 2; loglen = logend - logmsg; filter_message = logend + 2; if (filter_message[0] == 0) filter_message = NULL; } else { logmsg = filter_message; loglen = Ustrlen(filter_message); } } log_write(0, LOG_MAIN, \"cancelled by system filter%s%.*s\", colon, loglen, logmsg); } \/* Delivery can be restricted only to those recipients (if any) that the filter specified. *\/ else if (rc == FF_DELIVERED) { process_recipients = RECIP_IGNORE; if (addr_new) log_write(0, LOG_MAIN, \"original recipients ignored (system filter)\"); else log_write(0, LOG_MAIN, \"=> discarded (system filter)\"); } \/* If any new addresses were created by the filter, fake up a \"parent\" for them. This is necessary for pipes, etc., which are expected to have parents, and it also gives some sensible logging for others. Allow pipes, files, and autoreplies, and run them as the filter uid if set, otherwise as the current uid. *\/ if (addr_new) { int uid = (system_filter_uid_set)? system_filter_uid : geteuid(); int gid = (system_filter_gid_set)? system_filter_gid : getegid(); \/* The text \"system-filter\" is tested in transport_set_up_command() and in set_up_shell_command() in the pipe transport, to enable them to permit $recipients, so don't change it here without also changing it there. *\/ address_item *p = addr_new; address_item *parent = deliver_make_addr(US\"system-filter\", FALSE); parent->domain = string_copylc(qualify_domain_recipient); parent->local_part = US\"system-filter\"; \/* As part of this loop, we arrange for addr_last to end up pointing at the final address. This is used if we go on to add addresses for the original recipients. *\/ while (p) { if (parent->child_count == USHRT_MAX) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"system filter generated more \" \"than %d delivery addresses\", USHRT_MAX); parent->child_count++; p->parent = parent; if (testflag(p, af_pfr)) { uschar *tpname; uschar *type; p->uid = uid; p->gid = gid; setflag(p, af_uid_set); setflag(p, af_gid_set); setflag(p, af_allow_file); setflag(p, af_allow_pipe); setflag(p, af_allow_reply); \/* Find the name of the system filter's appropriate pfr transport *\/ if (p->address[0] == '|') { type = US\"pipe\"; tpname = system_filter_pipe_transport; address_pipe = p->address; } else if (p->address[0] == '>') { type = US\"reply\"; tpname = system_filter_reply_transport; } else { if (p->address[Ustrlen(p->address)-1] == '\/') { type = US\"directory\"; tpname = system_filter_directory_transport; } else { type = US\"file\"; tpname = system_filter_file_transport; } address_file = p->address; } \/* Now find the actual transport, first expanding the name. We have set address_file or address_pipe above. *\/ if (tpname) { uschar *tmp = expand_string(tpname); address_file = address_pipe = NULL; if (!tmp) p->message = string_sprintf(\"failed to expand \\\"%s\\\" as a \" \"system filter transport name\", tpname); tpname = tmp; } else p->message = string_sprintf(\"system_filter_%s_transport is unset\", type); if (tpname) { transport_instance *tp; for (tp = transports; tp; tp = tp->next) if (Ustrcmp(tp->name, tpname) == 0) { p->transport = tp; break; } if (!tp) p->message = string_sprintf(\"failed to find \\\"%s\\\" transport \" \"for system filter delivery\", tpname); } \/* If we couldn't set up a transport, defer the delivery, putting the error on the panic log as well as the main log. *\/ if (!p->transport) { address_item *badp = p; p = p->next; if (!addr_last) addr_new = p; else addr_last->next = p; badp->local_part = badp->address; \/* Needed for log line *\/ post_process_one(badp, DEFER, LOG_MAIN|LOG_PANIC, EXIM_DTYPE_ROUTER, 0); continue; } } \/* End of pfr handling *\/ \/* Either a non-pfr delivery, or we found a transport *\/ DEBUG(D_deliver|D_filter) debug_printf(\"system filter added %s\\n\", p->address); addr_last = p; p = p->next; } \/* Loop through all addr_new addresses *\/ } } \/* Scan the recipients list, and for every one that is not in the non- recipients tree, add an addr item to the chain of new addresses. If the pno value is non-negative, we must set the onetime parent from it. This which points to the relevant entry in the recipients list. This processing can be altered by the setting of the process_recipients variable, which is changed if recipients are to be ignored, failed, or deferred. This can happen as a result of system filter activity, or if the -Mg option is used to fail all of them. Duplicate addresses are handled later by a different tree structure; we can't just extend the non-recipients tree, because that will be re-written to the spool if the message is deferred, and in any case there are casing complications for local addresses. *\/ if (process_recipients != RECIP_IGNORE) for (i = 0; i < recipients_count; i++) if (!tree_search(tree_nonrecipients, recipients_list[i].address)) { recipient_item *r = recipients_list + i; address_item *new = deliver_make_addr(r->address, FALSE); new->prop.errors_address = r->errors_to; #ifdef SUPPORT_I18N if ((new->prop.utf8_msg = message_smtputf8)) { new->prop.utf8_downcvt = message_utf8_downconvert == 1; new->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1; DEBUG(D_deliver) debug_printf(\"utf8, downconvert %s\\n\", new->prop.utf8_downcvt ? \"yes\" : new->prop.utf8_downcvt_maybe ? \"ifneeded\" : \"no\"); } #endif if (r->pno >= 0) new->onetime_parent = recipients_list[r->pno].address; \/* If DSN support is enabled, set the dsn flags and the original receipt to be passed on to other DSN enabled MTAs *\/ new->dsn_flags = r->dsn_flags & rf_dsnflags; new->dsn_orcpt = r->orcpt; DEBUG(D_deliver) debug_printf(\"DSN: set orcpt: %s flags: %d\\n\", new->dsn_orcpt ? new->dsn_orcpt : US\"\", new->dsn_flags); switch (process_recipients) { \/* RECIP_DEFER is set when a system filter freezes a message. *\/ case RECIP_DEFER: new->next = addr_defer; addr_defer = new; break; \/* RECIP_FAIL_FILTER is set when a system filter has obeyed a \"fail\" command. *\/ case RECIP_FAIL_FILTER: new->message = filter_message ? filter_message : US\"delivery cancelled\"; setflag(new, af_pass_message); goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL_TIMEOUT is set when a message is frozen, but is older than the value in timeout_frozen_after. Treat non-bounce messages similarly to -Mg; for bounce messages we just want to discard, so don't put the address on the failed list. The timeout has already been logged. *\/ case RECIP_FAIL_TIMEOUT: new->message = US\"delivery cancelled; message timed out\"; goto RECIP_QUEUE_FAILED; \/* below *\/ \/* RECIP_FAIL is set when -Mg has been used. *\/ case RECIP_FAIL: new->message = US\"delivery cancelled by administrator\"; \/* Fall through *\/ \/* Common code for the failure cases above. If this is not a bounce message, put the address on the failed list so that it is used to create a bounce. Otherwise do nothing - this just discards the address. The incident has already been logged. *\/ RECIP_QUEUE_FAILED: if (sender_address[0]) { new->next = addr_failed; addr_failed = new; } break; \/* RECIP_FAIL_LOOP is set when there are too many Received: headers in the message. Process each address as a routing failure; if this is a bounce message, it will get frozen. *\/ case RECIP_FAIL_LOOP: new->message = US\"Too many \\\"Received\\\" headers - suspected mail loop\"; post_process_one(new, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); break; \/* Value should be RECIP_ACCEPT; take this as the safe default. *\/ default: if (!addr_new) addr_new = new; else addr_last->next = new; addr_last = new; break; } #ifndef DISABLE_EVENT if (process_recipients != RECIP_ACCEPT) { uschar * save_local = deliver_localpart; const uschar * save_domain = deliver_domain; uschar * addr = new->address, * errmsg = NULL; int start, end, dom; if (!parse_extract_address(addr, &errmsg, &start, &end, &dom, TRUE)) log_write(0, LOG_MAIN|LOG_PANIC, \"failed to parse address '%.100s': %s\\n\", addr, errmsg); else { deliver_localpart = string_copyn(addr+start, dom ? (dom-1) - start : end - start); deliver_domain = dom ? CUS string_copyn(addr+dom, end - dom) : CUS\"\"; event_raise(event_action, US\"msg:fail:internal\", new->message); deliver_localpart = save_local; deliver_domain = save_domain; } } #endif } DEBUG(D_deliver) { address_item *p; debug_printf(\"Delivery address list:\\n\"); for (p = addr_new; p; p = p->next) debug_printf(\" %s %s\\n\", p->address, p->onetime_parent ? p->onetime_parent : US\"\"); } \/* Set up the buffers used for copying over the file when delivering. *\/ deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE); deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE); \/* Until there are no more new addresses, handle each one as follows: . If this is a generated address (indicated by the presence of a parent pointer) then check to see whether it is a pipe, file, or autoreply, and if so, handle it directly here. The router that produced the address will have set the allow flags into the address, and also set the uid\/gid required. Having the routers generate new addresses and then checking them here at the outer level is tidier than making each router do the checking, and means that routers don't need access to the failed address queue. . Break up the address into local part and domain, and make lowercased versions of these strings. We also make unquoted versions of the local part. . Handle the percent hack for those domains for which it is valid. . For child addresses, determine if any of the parents have the same address. If so, generate a different string for previous delivery checking. Without this code, if the address spqr generates spqr via a forward or alias file, delivery of the generated spqr stops further attempts at the top level spqr, which is not what is wanted - it may have generated other addresses. . Check on the retry database to see if routing was previously deferred, but only if in a queue run. Addresses that are to be routed are put on the addr_route chain. Addresses that are to be deferred are put on the addr_defer chain. We do all the checking first, so as not to keep the retry database open any longer than necessary. . Now we run the addresses through the routers. A router may put the address on either the addr_local or the addr_remote chain for local or remote delivery, respectively, or put it on the addr_failed chain if it is undeliveable, or it may generate child addresses and put them on the addr_new chain, or it may defer an address. All the chain anchors are passed as arguments so that the routers can be called for verification purposes as well. . If new addresses have been generated by the routers, da capo. *\/ f.header_rewritten = FALSE; \/* No headers rewritten yet *\/ while (addr_new) \/* Loop until all addresses dealt with *\/ { address_item *addr, *parent; \/* Failure to open the retry database is treated the same as if it does not exist. In both cases, dbm_file is NULL. *\/ if (!(dbm_file = dbfn_open(US\"retry\", O_RDONLY, &dbblock, FALSE))) DEBUG(D_deliver|D_retry|D_route|D_hints_lookup) debug_printf(\"no retry data available\\n\"); \/* Scan the current batch of new addresses, to handle pipes, files and autoreplies, and determine which others are ready for routing. *\/ while (addr_new) { int rc; uschar *p; tree_node *tnode; dbdata_retry *domain_retry_record; dbdata_retry *address_retry_record; addr = addr_new; addr_new = addr->next; DEBUG(D_deliver|D_retry|D_route) { debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"Considering: %s\\n\", addr->address); } \/* Handle generated address that is a pipe or a file or an autoreply. *\/ if (testflag(addr, af_pfr)) { \/* If an autoreply in a filter could not generate a syntactically valid address, give up forthwith. Set af_ignore_error so that we don't try to generate a bounce. *\/ if (testflag(addr, af_bad_reply)) { addr->basic_errno = ERRNO_BADADDRESS2; addr->local_part = addr->address; addr->message = US\"filter autoreply generated syntactically invalid recipient\"; addr->prop.ignore_error = TRUE; (void) post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If two different users specify delivery to the same pipe or file or autoreply, there should be two different deliveries, so build a unique string that incorporates the original address, and use this for duplicate testing and recording delivery, and also for retrying. *\/ addr->unique = string_sprintf(\"%s:%s\", addr->address, addr->parent->unique + (testflag(addr->parent, af_homonym)? 3:0)); addr->address_retry_key = addr->domain_retry_key = string_sprintf(\"T:%s\", addr->unique); \/* If a filter file specifies two deliveries to the same pipe or file, we want to de-duplicate, but this is probably not wanted for two mail commands to the same address, where probably both should be delivered. So, we have to invent a different unique string in that case. Just keep piling '>' characters on the front. *\/ if (addr->address[0] == '>') { while (tree_search(tree_duplicates, addr->unique)) addr->unique = string_sprintf(\">%s\", addr->unique); } else if ((tnode = tree_search(tree_duplicates, addr->unique))) { DEBUG(D_deliver|D_route) debug_printf(\"%s is a duplicate address: discarded\\n\", addr->address); addr->dupof = tnode->data.ptr; addr->next = addr_duplicate; addr_duplicate = addr; continue; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); \/* Check for previous delivery *\/ if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->address); child_done(addr, tod_stamp(tod_log)); continue; } \/* Save for checking future duplicates *\/ tree_add_duplicate(addr->unique, addr); \/* Set local part and domain *\/ addr->local_part = addr->address; addr->domain = addr->parent->domain; \/* Ensure that the delivery is permitted. *\/ if (testflag(addr, af_file)) { if (!testflag(addr, af_allow_file)) { addr->basic_errno = ERRNO_FORBIDFILE; addr->message = US\"delivery to file forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (addr->address[0] == '|') { if (!testflag(addr, af_allow_pipe)) { addr->basic_errno = ERRNO_FORBIDPIPE; addr->message = US\"delivery to pipe forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } } else if (!testflag(addr, af_allow_reply)) { addr->basic_errno = ERRNO_FORBIDREPLY; addr->message = US\"autoreply forbidden\"; (void)post_process_one(addr, FAIL, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* with the next new address *\/ } \/* If the errno field is already set to BADTRANSPORT, it indicates failure to expand a transport string, or find the associated transport, or an unset transport when one is required. Leave this test till now so that the forbid errors are given in preference. *\/ if (addr->basic_errno == ERRNO_BADTRANSPORT) { (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; } \/* Treat \/dev\/null as a special case and abandon the delivery. This avoids having to specify a uid on the transport just for this case. Arrange for the transport name to be logged as \"**bypassed**\". *\/ if (Ustrcmp(addr->address, \"\/dev\/null\") == 0) { uschar *save = addr->transport->name; addr->transport->name = US\"**bypassed**\"; (void)post_process_one(addr, OK, LOG_MAIN, EXIM_DTYPE_TRANSPORT, '='); addr->transport->name = save; continue; \/* with the next new address *\/ } \/* Pipe, file, or autoreply delivery is to go ahead as a normal local delivery. *\/ DEBUG(D_deliver|D_route) debug_printf(\"queued for %s transport\\n\", addr->transport->name); addr->next = addr_local; addr_local = addr; continue; \/* with the next new address *\/ } \/* Handle normal addresses. First, split up into local part and domain, handling the %-hack if necessary. There is the possibility of a defer from a lookup in percent_hack_domains. *\/ if ((rc = deliver_split_address(addr)) == DEFER) { addr->message = US\"cannot check percent_hack_domains\"; addr->basic_errno = ERRNO_LISTDEFER; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Check to see if the domain is held. If so, proceed only if the delivery was forced by hand. *\/ deliver_domain = addr->domain; \/* set $domain *\/ if ( !forced && hold_domains && (rc = match_isinlist(addr->domain, (const uschar **)&hold_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != FAIL ) { if (rc == DEFER) { addr->message = US\"hold_domains lookup deferred\"; addr->basic_errno = ERRNO_LISTDEFER; } else { addr->message = US\"domain is held\"; addr->basic_errno = ERRNO_HELD; } (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_NONE, 0); continue; } \/* Now we can check for duplicates and previously delivered addresses. In order to do this, we have to generate a \"unique\" value for each address, because there may be identical actual addresses in a line of descendents. The \"unique\" field is initialized to the same value as the \"address\" field, but gets changed here to cope with identically-named descendents. *\/ for (parent = addr->parent; parent; parent = parent->parent) if (strcmpic(addr->address, parent->address) == 0) break; \/* If there's an ancestor with the same name, set the homonym flag. This influences how deliveries are recorded. Then add a prefix on the front of the unique address. We use \\n\\ where n starts at 0 and increases each time. It is unlikely to pass 9, but if it does, it may look odd but will still work. This means that siblings or cousins with the same names are treated as duplicates, which is what we want. *\/ if (parent) { setflag(addr, af_homonym); if (parent->unique[0] != '\\\\') addr->unique = string_sprintf(\"\\\\0\\\\%s\", addr->address); else addr->unique = string_sprintf(\"\\\\%c\\\\%s\", parent->unique[1] + 1, addr->address); } \/* Ensure that the domain in the unique field is lower cased, because domains are always handled caselessly. *\/ p = Ustrrchr(addr->unique, '@'); while (*p != 0) { *p = tolower(*p); p++; } DEBUG(D_deliver|D_route) debug_printf(\"unique = %s\\n\", addr->unique); if (tree_search(tree_nonrecipients, addr->unique)) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: discarded\\n\", addr->unique); child_done(addr, tod_stamp(tod_log)); continue; } \/* Get the routing retry status, saving the two retry keys (with and without the local part) for subsequent use. If there is no retry record for the standard address routing retry key, we look for the same key with the sender attached, because this form is used by the smtp transport after a 4xx response to RCPT when address_retry_include_sender is true. *\/ addr->domain_retry_key = string_sprintf(\"R:%s\", addr->domain); addr->address_retry_key = string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain); if (dbm_file) { domain_retry_record = dbfn_read(dbm_file, addr->domain_retry_key); if ( domain_retry_record && now - domain_retry_record->time_stamp > retry_data_expire ) domain_retry_record = NULL; \/* Ignore if too old *\/ address_retry_record = dbfn_read(dbm_file, addr->address_retry_key); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire ) address_retry_record = NULL; \/* Ignore if too old *\/ if (!address_retry_record) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); address_retry_record = dbfn_read(dbm_file, altkey); if ( address_retry_record && now - address_retry_record->time_stamp > retry_data_expire) address_retry_record = NULL; \/* Ignore if too old *\/ } } else domain_retry_record = address_retry_record = NULL; DEBUG(D_deliver|D_retry) { if (!domain_retry_record) debug_printf(\"no domain retry record\\n\"); if (!address_retry_record) debug_printf(\"no address retry record\\n\"); } \/* If we are sending a message down an existing SMTP connection, we must assume that the message which created the connection managed to route an address to that connection. We do not want to run the risk of taking a long time over routing here, because if we do, the server at the other end of the connection may time it out. This is especially true for messages with lots of addresses. For this kind of delivery, queue_running is not set, so we would normally route all addresses. We take a pragmatic approach and defer routing any addresses that have any kind of domain retry record. That is, we don't even look at their retry times. It doesn't matter if this doesn't work occasionally. This is all just an optimization, after all. The reason for not doing the same for address retries is that they normally arise from 4xx responses, not DNS timeouts. *\/ if (continue_hostname && domain_retry_record) { addr->message = US\"reusing SMTP connection skips previous routing defer\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* If we are in a queue run, defer routing unless there is no retry data or we've passed the next retry time, or this message is forced. In other words, ignore retry data when not in a queue run. However, if the domain retry time has expired, always allow the routing attempt. If it fails again, the address will be failed. This ensures that each address is routed at least once, even after long-term routing failures. If there is an address retry, check that too; just wait for the next retry time. This helps with the case when the temporary error on the address was really message-specific rather than address specific, since it allows other messages through. We also wait for the next retry time if this is a message sent down an existing SMTP connection (even though that will be forced). Otherwise there will be far too many attempts for an address that gets a 4xx error. In fact, after such an error, we should not get here because, the host should not be remembered as one this message needs. However, there was a bug that used to cause this to happen, so it is best to be on the safe side. Even if we haven't reached the retry time in the hints, there is one more check to do, which is for the ultimate address timeout. We only do this check if there is an address retry record and there is not a domain retry record; this implies that previous attempts to handle the address had the retry_use_local_parts option turned on. We use this as an approximation for the destination being like a local delivery, for example delivery over LMTP to an IMAP message store. In this situation users are liable to bump into their quota and thereby have intermittently successful deliveries, which keep the retry record fresh, which can lead to us perpetually deferring messages. *\/ else if ( ( f.queue_running && !f.deliver_force || continue_hostname ) && ( ( domain_retry_record && now < domain_retry_record->next_try && !domain_retry_record->expired ) || ( address_retry_record && now < address_retry_record->next_try ) ) && ( domain_retry_record || !address_retry_record || !retry_ultimate_address_timeout(addr->address_retry_key, addr->domain, address_retry_record, now) ) ) { addr->message = US\"retry time not reached\"; addr->basic_errno = ERRNO_RRETRY; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } \/* The domain is OK for routing. Remember if retry data exists so it can be cleaned up after a successful delivery. *\/ else { if (domain_retry_record || address_retry_record) setflag(addr, af_dr_retry_exists); addr->next = addr_route; addr_route = addr; DEBUG(D_deliver|D_route) debug_printf(\"%s: queued for routing\\n\", addr->address); } } \/* The database is closed while routing is actually happening. Requests to update it are put on a chain and all processed together at the end. *\/ if (dbm_file) dbfn_close(dbm_file); \/* If queue_domains is set, we don't even want to try routing addresses in those domains. During queue runs, queue_domains is forced to be unset. Optimize by skipping this pass through the addresses if nothing is set. *\/ if (!f.deliver_force && queue_domains) { address_item *okaddr = NULL; while (addr_route) { address_item *addr = addr_route; addr_route = addr->next; deliver_domain = addr->domain; \/* set $domain *\/ if ((rc = match_isinlist(addr->domain, (const uschar **)&queue_domains, 0, &domainlist_anchor, addr->domain_cache, MCL_DOMAIN, TRUE, NULL)) != OK) if (rc == DEFER) { addr->basic_errno = ERRNO_LISTDEFER; addr->message = US\"queue_domains lookup deferred\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } else { addr->next = okaddr; okaddr = addr; } else { addr->basic_errno = ERRNO_QUEUE_DOMAIN; addr->message = US\"domain is in queue_domains\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); } } addr_route = okaddr; } \/* Now route those addresses that are not deferred. *\/ while (addr_route) { int rc; address_item *addr = addr_route; const uschar *old_domain = addr->domain; uschar *old_unique = addr->unique; addr_route = addr->next; addr->next = NULL; \/* Just in case some router parameter refers to it. *\/ if (!(return_path = addr->prop.errors_address)) return_path = sender_address; \/* If a router defers an address, add a retry item. Whether or not to use the local part in the key is a property of the router. *\/ if ((rc = route_address(addr, &addr_local, &addr_remote, &addr_new, &addr_succeed, v_none)) == DEFER) retry_add_item(addr, addr->router->retry_use_local_part ? string_sprintf(\"R:%s@%s\", addr->local_part, addr->domain) : string_sprintf(\"R:%s\", addr->domain), 0); \/* Otherwise, if there is an existing retry record in the database, add retry items to delete both forms. We must also allow for the possibility of a routing retry that includes the sender address. Since the domain might have been rewritten (expanded to fully qualified) as a result of routing, ensure that the rewritten form is also deleted. *\/ else if (testflag(addr, af_dr_retry_exists)) { uschar *altkey = string_sprintf(\"%s:<%s>\", addr->address_retry_key, sender_address); retry_add_item(addr, altkey, rf_delete); retry_add_item(addr, addr->address_retry_key, rf_delete); retry_add_item(addr, addr->domain_retry_key, rf_delete); if (Ustrcmp(addr->domain, old_domain) != 0) retry_add_item(addr, string_sprintf(\"R:%s\", old_domain), rf_delete); } \/* DISCARD is given for :blackhole: and \"seen finish\". The event has been logged, but we need to ensure the address (and maybe parents) is marked done. *\/ if (rc == DISCARD) { address_done(addr, tod_stamp(tod_log)); continue; \/* route next address *\/ } \/* The address is finished with (failed or deferred). *\/ if (rc != OK) { (void)post_process_one(addr, rc, LOG_MAIN, EXIM_DTYPE_ROUTER, 0); continue; \/* route next address *\/ } \/* The address has been routed. If the router changed the domain, it will also have changed the unique address. We have to test whether this address has already been delivered, because it's the unique address that finally gets recorded. *\/ if ( addr->unique != old_unique && tree_search(tree_nonrecipients, addr->unique) != 0 ) { DEBUG(D_deliver|D_route) debug_printf(\"%s was previously delivered: \" \"discarded\\n\", addr->address); if (addr_remote == addr) addr_remote = addr->next; else if (addr_local == addr) addr_local = addr->next; } \/* If the router has same_domain_copy_routing set, we are permitted to copy the routing for any other addresses with the same domain. This is an optimisation to save repeated DNS lookups for \"standard\" remote domain routing. The option is settable only on routers that generate host lists. We play it very safe, and do the optimization only if the address is routed to a remote transport, there are no header changes, and the domain was not modified by the router. *\/ if ( addr_remote == addr && addr->router->same_domain_copy_routing && !addr->prop.extra_headers && !addr->prop.remove_headers && old_domain == addr->domain ) { address_item **chain = &addr_route; while (*chain) { address_item *addr2 = *chain; if (Ustrcmp(addr2->domain, addr->domain) != 0) { chain = &(addr2->next); continue; } \/* Found a suitable address; take it off the routing list and add it to the remote delivery list. *\/ *chain = addr2->next; addr2->next = addr_remote; addr_remote = addr2; \/* Copy the routing data *\/ addr2->domain = addr->domain; addr2->router = addr->router; addr2->transport = addr->transport; addr2->host_list = addr->host_list; addr2->fallback_hosts = addr->fallback_hosts; addr2->prop.errors_address = addr->prop.errors_address; copyflag(addr2, addr, af_hide_child); copyflag(addr2, addr, af_local_host_removed); DEBUG(D_deliver|D_route) debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\" \"routing %s\\n\" \"Routing for %s copied from %s\\n\", addr2->address, addr2->address, addr->address); } } } \/* Continue with routing the next address. *\/ } \/* Loop to process any child addresses that the routers created, and any rerouted addresses that got put back on the new chain. *\/ \/* Debugging: show the results of the routing *\/ DEBUG(D_deliver|D_retry|D_route) { address_item *p; debug_printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\"); debug_printf(\"After routing:\\n Local deliveries:\\n\"); for (p = addr_local; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Remote deliveries:\\n\"); for (p = addr_remote; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Failed addresses:\\n\"); for (p = addr_failed; p; p = p->next) debug_printf(\" %s\\n\", p->address); debug_printf(\" Deferred addresses:\\n\"); for (p = addr_defer; p; p = p->next) debug_printf(\" %s\\n\", p->address); } \/* Free any resources that were cached during routing. *\/ search_tidyup(); route_tidyup(); \/* These two variables are set only during routing, after check_local_user. Ensure they are not set in transports. *\/ local_user_gid = (gid_t)(-1); local_user_uid = (uid_t)(-1); \/* Check for any duplicate addresses. This check is delayed until after routing, because the flexibility of the routing configuration means that identical addresses with different parentage may end up being redirected to different addresses. Checking for duplicates too early (as we previously used to) makes this kind of thing not work. *\/ do_duplicate_check(&addr_local); do_duplicate_check(&addr_remote); \/* When acting as an MUA wrapper, we proceed only if all addresses route to a remote transport. The check that they all end up in one transaction happens in the do_remote_deliveries() function. *\/ if ( mua_wrapper && (addr_local || addr_failed || addr_defer) ) { address_item *addr; uschar *which, *colon, *msg; if (addr_local) { addr = addr_local; which = US\"local\"; } else if (addr_defer) { addr = addr_defer; which = US\"deferred\"; } else { addr = addr_failed; which = US\"failed\"; } while (addr->parent) addr = addr->parent; if (addr->message) { colon = US\": \"; msg = addr->message; } else colon = msg = US\"\"; \/* We don't need to log here for a forced failure as it will already have been logged. Defer will also have been logged, but as a defer, so we do need to do the failure logging. *\/ if (addr != addr_failed) log_write(0, LOG_MAIN, \"** %s routing yielded a %s delivery\", addr->address, which); \/* Always write an error to the caller *\/ fprintf(stderr, \"routing %s yielded a %s delivery%s%s\\n\", addr->address, which, colon, msg); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* If this is a run to continue deliveries to an external channel that is already set up, defer any local deliveries. *\/ if (continue_transport) { if (addr_defer) { address_item *addr = addr_defer; while (addr->next) addr = addr->next; addr->next = addr_local; } else addr_defer = addr_local; addr_local = NULL; } \/* Because address rewriting can happen in the routers, we should not really do ANY deliveries until all addresses have been routed, so that all recipients of the message get the same headers. However, this is in practice not always possible, since sometimes remote addresses give DNS timeouts for days on end. The pragmatic approach is to deliver what we can now, saving any rewritten headers so that at least the next lot of recipients benefit from the rewriting that has already been done. If any headers have been rewritten during routing, update the spool file to remember them for all subsequent deliveries. This can be delayed till later if there is only address to be delivered - if it succeeds the spool write need not happen. *\/ if ( f.header_rewritten && ( addr_local && (addr_local->next || addr_remote) || addr_remote && addr_remote->next ) ) { \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); f.header_rewritten = FALSE; } \/* If there are any deliveries to be and we do not already have the journal file, create it. This is used to record successful deliveries as soon as possible after each delivery is known to be complete. A file opened with O_APPEND is used so that several processes can run simultaneously. The journal is just insurance against crashes. When the spool file is ultimately updated at the end of processing, the journal is deleted. If a journal is found to exist at the start of delivery, the addresses listed therein are added to the non-recipients. *\/ if (addr_local || addr_remote) { if (journal_fd < 0) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if ((journal_fd = Uopen(fname, #ifdef O_CLOEXEC O_CLOEXEC | #endif O_WRONLY|O_APPEND|O_CREAT|O_EXCL, SPOOL_MODE)) < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't open journal file %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } \/* Set the close-on-exec flag, make the file owned by Exim, and ensure that the mode is correct - the group setting doesn't always seem to get set automatically. *\/ if( fchown(journal_fd, exim_uid, exim_gid) || fchmod(journal_fd, SPOOL_MODE) #ifndef O_CLOEXEC || fcntl(journal_fd, F_SETFD, fcntl(journal_fd, F_GETFD) | FD_CLOEXEC) #endif ) { int ret = Uunlink(fname); log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't set perms on journal file %s: %s\", fname, strerror(errno)); if(ret && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); return DELIVER_NOT_ATTEMPTED; } } } else if (journal_fd >= 0) { close(journal_fd); journal_fd = -1; } \/* Now we can get down to the business of actually doing deliveries. Local deliveries are done first, then remote ones. If ever the problems of how to handle fallback transports are figured out, this section can be put into a loop for handling fallbacks, though the uid switching will have to be revised. *\/ \/* Precompile a regex that is used to recognize a parameter in response to an LHLO command, if is isn't already compiled. This may be used on both local and remote LMTP deliveries. *\/ if (!regex_IGNOREQUOTA) regex_IGNOREQUOTA = regex_must_compile(US\"\\\\n250[\\\\s\\\\-]IGNOREQUOTA(\\\\s|\\\\n|$)\", FALSE, TRUE); \/* Handle local deliveries *\/ if (addr_local) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Local deliveries >>>>>>>>>>>>>>>>\\n\"); do_local_deliveries(); f.disable_logging = FALSE; } \/* If queue_run_local is set, we do not want to attempt any remote deliveries, so just queue them all. *\/ if (f.queue_run_local) while (addr_remote) { address_item *addr = addr_remote; addr_remote = addr->next; addr->next = NULL; addr->basic_errno = ERRNO_LOCAL_ONLY; addr->message = US\"remote deliveries suppressed\"; (void)post_process_one(addr, DEFER, LOG_MAIN, EXIM_DTYPE_TRANSPORT, 0); } \/* Handle remote deliveries *\/ if (addr_remote) { DEBUG(D_deliver|D_transport) debug_printf(\">>>>>>>>>>>>>>>> Remote deliveries >>>>>>>>>>>>>>>>\\n\"); \/* Precompile some regex that are used to recognize parameters in response to an EHLO command, if they aren't already compiled. *\/ deliver_init(); \/* Now sort the addresses if required, and do the deliveries. The yield of do_remote_deliveries is FALSE when mua_wrapper is set and all addresses cannot be delivered in one transaction. *\/ if (remote_sort_domains) sort_remote_deliveries(); if (!do_remote_deliveries(FALSE)) { log_write(0, LOG_MAIN, \"** mua_wrapper is set but recipients cannot all \" \"be delivered in one transaction\"); fprintf(stderr, \"delivery to smarthost failed (configuration problem)\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = addr_defer = NULL; \/* So that we remove the message *\/ goto DELIVERY_TIDYUP; } \/* See if any of the addresses that failed got put on the queue for delivery to their fallback hosts. We do it this way because often the same fallback host is used for many domains, so all can be sent in a single transaction (if appropriately configured). *\/ if (addr_fallback && !mua_wrapper) { DEBUG(D_deliver) debug_printf(\"Delivering to fallback hosts\\n\"); addr_remote = addr_fallback; addr_fallback = NULL; if (remote_sort_domains) sort_remote_deliveries(); do_remote_deliveries(TRUE); } f.disable_logging = FALSE; } \/* All deliveries are now complete. Ignore SIGTERM during this tidying up phase, to minimize cases of half-done things. *\/ DEBUG(D_deliver) debug_printf(\">>>>>>>>>>>>>>>> deliveries are done >>>>>>>>>>>>>>>>\\n\"); cancel_cutthrough_connection(TRUE, US\"deliveries are done\"); \/* Root privilege is no longer needed *\/ exim_setugid(exim_uid, exim_gid, FALSE, US\"post-delivery tidying\"); set_process_info(\"tidying up after delivering %s\", message_id); signal(SIGTERM, SIG_IGN); \/* When we are acting as an MUA wrapper, the smtp transport will either have succeeded for all addresses, or failed them all in normal cases. However, there are some setup situations (e.g. when a named port does not exist) that cause an immediate exit with deferral of all addresses. Convert those into failures. We do not ever want to retry, nor do we want to send a bounce message. *\/ if (mua_wrapper) { if (addr_defer) { address_item *addr, *nextaddr; for (addr = addr_defer; addr; addr = nextaddr) { log_write(0, LOG_MAIN, \"** %s mua_wrapper forced failure for deferred \" \"delivery\", addr->address); nextaddr = addr->next; addr->next = addr_failed; addr_failed = addr; } addr_defer = NULL; } \/* Now all should either have succeeded or failed. *\/ if (!addr_failed) final_yield = DELIVER_MUA_SUCCEEDED; else { host_item * host; uschar *s = addr_failed->user_message; if (!s) s = addr_failed->message; fprintf(stderr, \"Delivery failed: \"); if (addr_failed->basic_errno > 0) { fprintf(stderr, \"%s\", strerror(addr_failed->basic_errno)); if (s) fprintf(stderr, \": \"); } if ((host = addr_failed->host_used)) fprintf(stderr, \"H=%s [%s]: \", host->name, host->address); if (s) fprintf(stderr, \"%s\", CS s); else if (addr_failed->basic_errno <= 0) fprintf(stderr, \"unknown error\"); fprintf(stderr, \"\\n\"); final_yield = DELIVER_MUA_FAILED; addr_failed = NULL; } } \/* In a normal configuration, we now update the retry database. This is done in one fell swoop at the end in order not to keep opening and closing (and locking) the database. The code for handling retries is hived off into a separate module for convenience. We pass it the addresses of the various chains, because deferred addresses can get moved onto the failed chain if the retry cutoff time has expired for all alternative destinations. Bypass the updating of the database if the -N flag is set, which is a debugging thing that prevents actual delivery. *\/ else if (!f.dont_deliver) retry_update(&addr_defer, &addr_failed, &addr_succeed); \/* Send DSN for successful messages if requested *\/ addr_senddsn = NULL; for (addr_dsntmp = addr_succeed; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { \/* af_ignore_error not honored here. it's not an error *\/ DEBUG(D_deliver) debug_printf(\"DSN: processing router : %s\\n\" \"DSN: processing successful delivery address: %s\\n\" \"DSN: Sender_address: %s\\n\" \"DSN: orcpt: %s flags: %d\\n\" \"DSN: envid: %s ret: %d\\n\" \"DSN: Final recipient: %s\\n\" \"DSN: Remote SMTP server supports DSN: %d\\n\", addr_dsntmp->router ? addr_dsntmp->router->name : US\"(unknown)\", addr_dsntmp->address, sender_address, addr_dsntmp->dsn_orcpt ? addr_dsntmp->dsn_orcpt : US\"NULL\", addr_dsntmp->dsn_flags, dsn_envid ? dsn_envid : US\"NULL\", dsn_ret, addr_dsntmp->address, addr_dsntmp->dsn_aware ); \/* send report if next hop not DSN aware or a router flagged \"last DSN hop\" and a report was requested *\/ if ( ( addr_dsntmp->dsn_aware != dsn_support_yes || addr_dsntmp->dsn_flags & rf_dsnlasthop ) && addr_dsntmp->dsn_flags & rf_notify_success ) { \/* copy and relink address_item and send report with all of them at once later *\/ address_item * addr_next = addr_senddsn; addr_senddsn = store_get(sizeof(address_item)); *addr_senddsn = *addr_dsntmp; addr_senddsn->next = addr_next; } else DEBUG(D_deliver) debug_printf(\"DSN: not sending DSN success message\\n\"); } if (addr_senddsn) { pid_t pid; int fd; \/* create exim process to send message *\/ pid = child_open_exim(&fd); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim returns: %d\\n\", pid); if (pid < 0) \/* Creation of child failed *\/ { log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); DEBUG(D_deliver) debug_printf(\"DSN: child_open_exim failed\\n\"); } else \/* Creation of child succeeded *\/ { FILE * f = fdopen(fd, \"wb\"); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ uschar * bound; transport_ctx tctx = {{0}}; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", sender_address); \/* build unique id for MIME boundary *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); DEBUG(D_deliver) debug_printf(\"DSN: MIME boundary: %s\\n\", bound); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-generated\\n\" \"From: Mail Delivery System \\n\" \"To: %s\\n\" \"Subject: Delivery Status Notification\\n\" \"Content-Type: multipart\/report; report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\\n\" \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\" \"This message was created automatically by mail delivery software.\\n\" \" ----- The following addresses had successful delivery notifications -----\\n\", qualify_domain_sender, sender_address, bound, bound); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) fprintf(f, \"<%s> (relayed %s)\\n\\n\", addr_dsntmp->address, addr_dsntmp->dsn_flags & rf_dsnlasthop ? \"via non DSN router\" : addr_dsntmp->dsn_aware == dsn_support_no ? \"to non-DSN-aware mailer\" : \"via non \\\"Remote SMTP\\\" router\" ); fprintf(f, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for (addr_dsntmp = addr_senddsn; addr_dsntmp; addr_dsntmp = addr_dsntmp->next) { if (addr_dsntmp->dsn_orcpt) fprintf(f,\"Original-Recipient: %s\\n\", addr_dsntmp->dsn_orcpt); fprintf(f, \"Action: delivered\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 2.0.0\\n\", addr_dsntmp->address); if (addr_dsntmp->host_used && addr_dsntmp->host_used->name) fprintf(f, \"Remote-MTA: dns; %s\\nDiagnostic-Code: smtp; 250 Ok\\n\\n\", addr_dsntmp->host_used->name); else fprintf(f, \"Diagnostic-Code: X-Exim; relayed via non %s router\\n\\n\", addr_dsntmp->dsn_flags & rf_dsnlasthop ? \"DSN\" : \"SMTP\"); } fprintf(f, \"--%s\\nContent-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ tctx.u.fd = fd; tctx.options = topt_add_return_path | topt_no_body; \/*XXX hmm, retval ignored. Could error for any number of reasons, and they are not handled. *\/ transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); fclose(f); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ } } \/* If any addresses failed, we must send a message to somebody, unless af_ignore_error is set, in which case no action is taken. It is possible for several messages to get sent if there are addresses with different requirements. *\/ while (addr_failed) { pid_t pid; int fd; uschar *logtod = tod_stamp(tod_log); address_item *addr; address_item *handled_addr = NULL; address_item **paddr; address_item *msgchain = NULL; address_item **pmsgchain = &msgchain; \/* There are weird cases when logging is disabled in the transport. However, there may not be a transport (address failed by a router). *\/ f.disable_logging = FALSE; if (addr_failed->transport) f.disable_logging = addr_failed->transport->disable_logging; DEBUG(D_deliver) debug_printf(\"processing failed address %s\\n\", addr_failed->address); \/* There are only two ways an address in a bounce message can get here: (1) When delivery was initially deferred, but has now timed out (in the call to retry_update() above). We can detect this by testing for af_retry_timedout. If the address does not have its own errors address, we arrange to ignore the error. (2) If delivery failures for bounce messages are being ignored. We can detect this by testing for af_ignore_error. This will also be set if a bounce message has been autothawed and the ignore_bounce_errors_after time has passed. It might also be set if a router was explicitly configured to ignore errors (errors_to = \"\"). If neither of these cases obtains, something has gone wrong. Log the incident, but then ignore the error. *\/ if (sender_address[0] == 0 && !addr_failed->prop.errors_address) { if ( !testflag(addr_failed, af_retry_timedout) && !addr_failed->prop.ignore_error) log_write(0, LOG_MAIN|LOG_PANIC, \"internal error: bounce message \" \"failure is neither frozen nor ignored (it's been ignored)\"); addr_failed->prop.ignore_error = TRUE; } \/* If the first address on the list has af_ignore_error set, just remove it from the list, throw away any saved message file, log it, and mark the recipient done. *\/ if ( addr_failed->prop.ignore_error || addr_failed->dsn_flags & (rf_dsnflags & ~rf_notify_failure) ) { addr = addr_failed; addr_failed = addr->next; if (addr->return_filename) Uunlink(addr->return_filename); #ifndef DISABLE_EVENT msg_event_raise(US\"msg:fail:delivery\", addr); #endif log_write(0, LOG_MAIN, \"%s%s%s%s: error ignored\", addr->address, !addr->parent ? US\"\" : US\" <\", !addr->parent ? US\"\" : addr->parent->address, !addr->parent ? US\"\" : US\">\"); address_done(addr, logtod); child_done(addr, logtod); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Otherwise, handle the sending of a message. Find the error address for the first address, then send a message that includes all failed addresses that have the same error address. Note the bounce_recipient is a global so that it can be accessed by $bounce_recipient while creating a customized error message. *\/ else { if (!(bounce_recipient = addr_failed->prop.errors_address)) bounce_recipient = sender_address; \/* Make a subprocess to send a message *\/ if ((pid = child_open_exim(&fd)) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Process %d (parent %d) failed to \" \"create child process to send failure message: %s\", getpid(), getppid(), strerror(errno)); \/* Creation of child succeeded *\/ else { int ch, rc; int filecount = 0; int rcount = 0; uschar *bcc, *emf_text; FILE * fp = fdopen(fd, \"wb\"); FILE * emf = NULL; BOOL to_sender = strcmpic(sender_address, bounce_recipient) == 0; int max = (bounce_return_size_limit\/DELIVER_IN_BUFFER_SIZE + 1) * DELIVER_IN_BUFFER_SIZE; uschar * bound; uschar *dsnlimitmsg; uschar *dsnnotifyhdr; int topt; DEBUG(D_deliver) debug_printf(\"sending error message to: %s\\n\", bounce_recipient); \/* Scan the addresses for all that have the same errors address, removing them from the addr_failed chain, and putting them on msgchain. *\/ paddr = &addr_failed; for (addr = addr_failed; addr; addr = *paddr) if (Ustrcmp(bounce_recipient, addr->prop.errors_address ? addr->prop.errors_address : sender_address) == 0) { \/* The same - dechain *\/ *paddr = addr->next; *pmsgchain = addr; addr->next = NULL; pmsgchain = &(addr->next); } else paddr = &addr->next; \/* Not the same; skip *\/ \/* Include X-Failed-Recipients: for automatic interpretation, but do not let any one header line get too long. We do this by starting a new header every 50 recipients. Omit any addresses for which the \"hide_child\" flag is set. *\/ for (addr = msgchain; addr; addr = addr->next) { if (testflag(addr, af_hide_child)) continue; if (rcount >= 50) { fprintf(fp, \"\\n\"); rcount = 0; } fprintf(fp, \"%s%s\", rcount++ == 0 ? \"X-Failed-Recipients: \" : \",\\n \", testflag(addr, af_pfr) && addr->parent ? string_printing(addr->parent->address) : string_printing(addr->address)); } if (rcount > 0) fprintf(fp, \"\\n\"); \/* Output the standard headers *\/ if (errors_reply_to) fprintf(fp, \"Reply-To: %s\\n\", errors_reply_to); fprintf(fp, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(fp); fprintf(fp, \"To: %s\\n\", bounce_recipient); \/* generate boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(fp, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); \/* Open a template file if one is provided. Log failure to open, but carry on - default texts will be used. *\/ if (bounce_message_file) if (!(emf = Ufopen(bounce_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for error \" \"message texts: %s\", bounce_message_file, strerror(errno)); \/* Quietly copy to configured additional addresses if required. *\/ if ((bcc = moan_check_errorcopy(bounce_recipient))) fprintf(fp, \"Bcc: %s\\n\", bcc); \/* The texts for the message can be read from a template file; if there isn't one, or if it is too short, built-in texts are used. The first emf text is a Subject: and any other headers. *\/ if ((emf_text = next_emf(emf, US\"header\"))) fprintf(fp, \"%s\\n\", emf_text); else fprintf(fp, \"Subject: Mail delivery failed%s\\n\\n\", to_sender? \": returning message to sender\" : \"\"); \/* output human readable part as text\/plain section *\/ fprintf(fp, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((emf_text = next_emf(emf, US\"intro\"))) fprintf(fp, \"%s\", CS emf_text); else { fprintf(fp, \/* This message has been reworded several times. It seems to be confusing to somebody, however it is worded. I have retreated to the original, simple wording. *\/ \"This message was created automatically by mail delivery software.\\n\"); if (bounce_message_text) fprintf(fp, \"%s\", CS bounce_message_text); if (to_sender) fprintf(fp, \"\\nA message that you sent could not be delivered to one or more of its\\n\" \"recipients. This is a permanent error. The following address(es) failed:\\n\"); else fprintf(fp, \"\\nA message sent by\\n\\n <%s>\\n\\n\" \"could not be delivered to one or more of its recipients. The following\\n\" \"address(es) failed:\\n\", sender_address); } fputc('\\n', fp); \/* Process the addresses, leaving them on the msgchain if they have a file name for a return message. (There has already been a check in post_process_one() for the existence of data in the message file.) A TRUE return from print_address_information() means that the address is not hidden. *\/ paddr = &msgchain; for (addr = msgchain; addr; addr = *paddr) { if (print_address_information(addr, fp, US\" \", US\"\\n \", US\"\")) print_address_error(addr, fp, US\"\"); \/* End the final line for the address *\/ fputc('\\n', fp); \/* Leave on msgchain if there's a return file. *\/ if (addr->return_file >= 0) { paddr = &(addr->next); filecount++; } \/* Else save so that we can tick off the recipient when the message is sent. *\/ else { *paddr = addr->next; addr->next = handled_addr; handled_addr = addr; } } fputc('\\n', fp); \/* Get the next text, whether we need it or not, so as to be positioned for the one after. *\/ emf_text = next_emf(emf, US\"generated text\"); \/* If there were any file messages passed by the local transports, include them in the message. Then put the address on the handled chain. In the case of a batch of addresses that were all sent to the same transport, the return_file field in all of them will contain the same fd, and the return_filename field in the *last* one will be set (to the name of the file). *\/ if (msgchain) { address_item *nextaddr; if (emf_text) fprintf(fp, \"%s\", CS emf_text); else fprintf(fp, \"The following text was generated during the delivery \" \"attempt%s:\\n\", (filecount > 1)? \"s\" : \"\"); for (addr = msgchain; addr; addr = nextaddr) { FILE *fm; address_item *topaddr = addr; \/* List all the addresses that relate to this file *\/ fputc('\\n', fp); while(addr) \/* Insurance *\/ { print_address_information(addr, fp, US\"------ \", US\"\\n \", US\" ------\\n\"); if (addr->return_filename) break; addr = addr->next; } fputc('\\n', fp); \/* Now copy the file *\/ if (!(fm = Ufopen(addr->return_filename, \"rb\"))) fprintf(fp, \" +++ Exim error... failed to open text file: %s\\n\", strerror(errno)); else { while ((ch = fgetc(fm)) != EOF) fputc(ch, fp); (void)fclose(fm); } Uunlink(addr->return_filename); \/* Can now add to handled chain, first fishing off the next address on the msgchain. *\/ nextaddr = addr->next; addr->next = handled_addr; handled_addr = topaddr; } fputc('\\n', fp); } \/* output machine readable part *\/ #ifdef SUPPORT_I18N if (message_smtputf8) fprintf(fp, \"--%s\\n\" \"Content-type: message\/global-delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); else #endif fprintf(fp, \"--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(fp, \"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(fp, \"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', fp); for (addr = handled_addr; addr; addr = addr->next) { host_item * hu; fprintf(fp, \"Action: failed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 5.0.0\\n\", addr->address); if ((hu = addr->host_used) && hu->name) { fprintf(fp, \"Remote-MTA: dns; %s\\n\", hu->name); #ifdef EXPERIMENTAL_DSN_INFO { const uschar * s; if (hu->address) { uschar * p = hu->port == 25 ? US\"\" : string_sprintf(\":%d\", hu->port); fprintf(fp, \"Remote-MTA: X-ip; [%s]%s\\n\", hu->address, p); } if ((s = addr->smtp_greeting) && *s) fprintf(fp, \"X-Remote-MTA-smtp-greeting: X-str; %s\\n\", s); if ((s = addr->helo_response) && *s) fprintf(fp, \"X-Remote-MTA-helo-response: X-str; %s\\n\", s); if ((s = addr->message) && *s) fprintf(fp, \"X-Exim-Diagnostic: X-str; %s\\n\", s); } #endif print_dsn_diagnostic_code(addr, fp); } fputc('\\n', fp); } \/* Now copy the message, trying to give an intelligible comment if it is too long for it all to be copied. The limit isn't strictly applied because of the buffering. There is, however, an option to suppress copying altogether. *\/ emf_text = next_emf(emf, US\"copy\"); \/* add message body we ignore the intro text from template and add the text for bounce_return_size_limit at the end. bounce_return_message is ignored in case RET= is defined we honor these values otherwise bounce_return_body is honored. bounce_return_size_limit is always honored. *\/ fprintf(fp, \"--%s\\n\", bound); dsnlimitmsg = US\"X-Exim-DSN-Information: Due to administrative limits only headers are returned\"; dsnnotifyhdr = NULL; topt = topt_add_return_path; \/* RET=HDRS? top priority *\/ if (dsn_ret == dsn_ret_hdrs) topt |= topt_no_body; else { struct stat statbuf; \/* no full body return at all? *\/ if (!bounce_return_body) { topt |= topt_no_body; \/* add header if we overrule RET=FULL *\/ if (dsn_ret == dsn_ret_full) dsnnotifyhdr = dsnlimitmsg; } \/* line length limited... return headers only if oversize *\/ \/* size limited ... return headers only if limit reached *\/ else if ( max_received_linelength > bounce_return_linesize_limit || ( bounce_return_size_limit > 0 && fstat(deliver_datafile, &statbuf) == 0 && statbuf.st_size > max ) ) { topt |= topt_no_body; dsnnotifyhdr = dsnlimitmsg; } } #ifdef SUPPORT_I18N if (message_smtputf8) fputs(topt & topt_no_body ? \"Content-type: message\/global-headers\\n\\n\" : \"Content-type: message\/global\\n\\n\", fp); else #endif fputs(topt & topt_no_body ? \"Content-type: text\/rfc822-headers\\n\\n\" : \"Content-type: message\/rfc822\\n\\n\", fp); fflush(fp); transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ { \/* Dummy transport for headers add *\/ transport_ctx tctx = {{0}}; transport_instance tb = {0}; tctx.u.fd = fileno(fp); tctx.tblock = &tb; tctx.options = topt; tb.add_headers = dsnnotifyhdr; \/*XXX no checking for failure! buggy! *\/ transport_write_message(&tctx, 0); } fflush(fp); \/* we never add the final text. close the file *\/ if (emf) (void)fclose(emf); fprintf(fp, \"\\n--%s--\\n\", bound); \/* Close the file, which should send an EOF to the child process that is receiving the message. Wait for it to finish. *\/ (void)fclose(fp); rc = child_close(pid, 0); \/* Waits for child to close, no timeout *\/ \/* In the test harness, let the child do it's thing first. *\/ if (f.running_in_test_harness) millisleep(500); \/* If the process failed, there was some disaster in setting up the error message. Unless the message is very old, ensure that addr_defer is non-null, which will have the effect of leaving the message on the spool. The failed addresses will get tried again next time. However, we don't really want this to happen too often, so freeze the message unless there are some genuine deferred addresses to try. To do this we have to call spool_write_header() here, because with no genuine deferred addresses the normal code below doesn't get run. *\/ if (rc != 0) { uschar *s = US\"\"; if (now - received_time.tv_sec < retry_maximum_timeout && !addr_defer) { addr_defer = (address_item *)(+1); f.deliver_freeze = TRUE; deliver_frozen_at = time(NULL); \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); s = US\" (frozen)\"; } deliver_msglog(\"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); log_write(0, LOG_MAIN, \"Process failed (%d) when writing error message \" \"to %s%s\", rc, bounce_recipient, s); } \/* The message succeeded. Ensure that the recipients that failed are now marked finished with on the spool and their parents updated. *\/ else { for (addr = handled_addr; addr; addr = addr->next) { address_done(addr, logtod); child_done(addr, logtod); } \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } } } } f.disable_logging = FALSE; \/* In case left set *\/ \/* Come here from the mua_wrapper case if routing goes wrong *\/ DELIVERY_TIDYUP: \/* If there are now no deferred addresses, we are done. Preserve the message log if so configured, and we are using them. Otherwise, sling it. Then delete the message itself. *\/ if (!addr_defer) { uschar * fname; if (message_logs) { fname = spool_fname(US\"msglog\", message_subdir, id, US\"\"); if (preserve_message_logs) { int rc; uschar * moname = spool_fname(US\"msglog.OLD\", US\"\", id, US\"\"); if ((rc = Urename(fname, moname)) < 0) { (void)directory_make(spool_directory, spool_sname(US\"msglog.OLD\", US\"\"), MSGLOG_DIRECTORY_MODE, TRUE); rc = Urename(fname, moname); } if (rc < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to move %s to the \" \"msglog.OLD directory\", fname); } else if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); } \/* Remove the two message files. *\/ fname = spool_fname(US\"input\", message_subdir, id, US\"-D\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); fname = spool_fname(US\"input\", message_subdir, id, US\"-H\"); if (Uunlink(fname) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Log the end of this message, with queue time if requested. *\/ if (LOGGING(queue_time_overall)) log_write(0, LOG_MAIN, \"Completed QT=%s\", string_timesince(&received_time)); else log_write(0, LOG_MAIN, \"Completed\"); \/* Unset deliver_freeze so that we won't try to move the spool files further down *\/ f.deliver_freeze = FALSE; #ifndef DISABLE_EVENT (void) event_raise(event_action, US\"msg:complete\", NULL); #endif } \/* If there are deferred addresses, we are keeping this message because it is not yet completed. Lose any temporary files that were catching output from pipes for any of the deferred addresses, handle one-time aliases, and see if the message has been on the queue for so long that it is time to send a warning message to the sender, unless it is a mailer-daemon. If all deferred addresses have the same domain, we can set deliver_domain for the expansion of delay_warning_ condition - if any of them are pipes, files, or autoreplies, use the parent's domain. If all the deferred addresses have an error number that indicates \"retry time not reached\", skip sending the warning message, because it won't contain the reason for the delay. It will get sent at the next real delivery attempt. However, if at least one address has tried, we'd better include all of them in the message. If we can't make a process to send the message, don't worry. For mailing list expansions we want to send the warning message to the mailing list manager. We can't do a perfect job here, as some addresses may have different errors addresses, but if we take the errors address from each deferred address it will probably be right in most cases. If addr_defer == +1, it means there was a problem sending an error message for failed addresses, and there were no \"real\" deferred addresses. The value was set just to keep the message on the spool, so there is nothing to do here. *\/ else if (addr_defer != (address_item *)(+1)) { address_item *addr; uschar *recipients = US\"\"; BOOL delivery_attempted = FALSE; deliver_domain = testflag(addr_defer, af_pfr) ? addr_defer->parent->domain : addr_defer->domain; for (addr = addr_defer; addr; addr = addr->next) { address_item *otaddr; if (addr->basic_errno > ERRNO_RETRY_BASE) delivery_attempted = TRUE; if (deliver_domain) { const uschar *d = testflag(addr, af_pfr) ? addr->parent->domain : addr->domain; \/* The domain may be unset for an address that has never been routed because the system filter froze the message. *\/ if (!d || Ustrcmp(d, deliver_domain) != 0) deliver_domain = NULL; } if (addr->return_filename) Uunlink(addr->return_filename); \/* Handle the case of one-time aliases. If any address in the ancestry of this one is flagged, ensure it is in the recipients list, suitably flagged, and that its parent is marked delivered. *\/ for (otaddr = addr; otaddr; otaddr = otaddr->parent) if (otaddr->onetime_parent) break; if (otaddr) { int i; int t = recipients_count; for (i = 0; i < recipients_count; i++) { uschar *r = recipients_list[i].address; if (Ustrcmp(otaddr->onetime_parent, r) == 0) t = i; if (Ustrcmp(otaddr->address, r) == 0) break; } \/* Didn't find the address already in the list, and did find the ultimate parent's address in the list, and they really are different (i.e. not from an identity-redirect). After adding the recipient, update the errors address in the recipients list. *\/ if ( i >= recipients_count && t < recipients_count && Ustrcmp(otaddr->address, otaddr->parent->address) != 0) { DEBUG(D_deliver) debug_printf(\"one_time: adding %s in place of %s\\n\", otaddr->address, otaddr->parent->address); receive_add_recipient(otaddr->address, t); recipients_list[recipients_count-1].errors_to = otaddr->prop.errors_address; tree_add_nonrecipient(otaddr->parent->address); update_spool = TRUE; } } \/* Except for error messages, ensure that either the errors address for this deferred address or, if there is none, the sender address, is on the list of recipients for a warning message. *\/ if (sender_address[0]) { uschar * s = addr->prop.errors_address; if (!s) s = sender_address; if (Ustrstr(recipients, s) == NULL) recipients = string_sprintf(\"%s%s%s\", recipients, recipients[0] ? \",\" : \"\", s); } } \/* Send a warning message if the conditions are right. If the condition check fails because of a lookup defer, there is nothing we can do. The warning is not sent. Another attempt will be made at the next delivery attempt (if it also defers). *\/ if ( !f.queue_2stage && delivery_attempted && ( !(addr_defer->dsn_flags & rf_dsnflags) || addr_defer->dsn_flags & rf_notify_delay ) && delay_warning[1] > 0 && sender_address[0] != 0 && ( !delay_warning_condition || expand_check_condition(delay_warning_condition, US\"delay_warning\", US\"option\") ) ) { int count; int show_time; int queue_time = time(NULL) - received_time.tv_sec; \/* When running in the test harness, there's an option that allows us to fudge this time so as to get repeatability of the tests. Take the first time off the list. In queue runs, the list pointer gets updated in the calling process. *\/ if (f.running_in_test_harness && fudged_queue_times[0] != 0) { int qt = readconf_readtime(fudged_queue_times, '\/', FALSE); if (qt >= 0) { DEBUG(D_deliver) debug_printf(\"fudged queue_times = %s\\n\", fudged_queue_times); queue_time = qt; } } \/* See how many warnings we should have sent by now *\/ for (count = 0; count < delay_warning[1]; count++) if (queue_time < delay_warning[count+2]) break; show_time = delay_warning[count+1]; if (count >= delay_warning[1]) { int extra; int last_gap = show_time; if (count > 1) last_gap -= delay_warning[count]; extra = (queue_time - delay_warning[count+1])\/last_gap; show_time += last_gap * extra; count += extra; } DEBUG(D_deliver) { debug_printf(\"time on queue = %s\\n\", readconf_printtime(queue_time)); debug_printf(\"warning counts: required %d done %d\\n\", count, warning_count); } \/* We have computed the number of warnings there should have been by now. If there haven't been enough, send one, and up the count to what it should have been. *\/ if (warning_count < count) { header_line *h; int fd; pid_t pid = child_open_exim(&fd); if (pid > 0) { uschar *wmf_text; FILE *wmf = NULL; FILE *f = fdopen(fd, \"wb\"); uschar * bound; transport_ctx tctx = {{0}}; if (warn_message_file) if (!(wmf = Ufopen(warn_message_file, \"rb\"))) log_write(0, LOG_MAIN|LOG_PANIC, \"Failed to open %s for warning \" \"message texts: %s\", warn_message_file, strerror(errno)); warnmsg_recipients = recipients; warnmsg_delay = queue_time < 120*60 ? string_sprintf(\"%d minutes\", show_time\/60) : string_sprintf(\"%d hours\", show_time\/3600); if (errors_reply_to) fprintf(f, \"Reply-To: %s\\n\", errors_reply_to); fprintf(f, \"Auto-Submitted: auto-replied\\n\"); moan_write_from(f); fprintf(f, \"To: %s\\n\", recipients); \/* generated boundary string and output MIME-Headers *\/ bound = string_sprintf(TIME_T_FMT \"-eximdsn-%d\", time(NULL), rand()); fprintf(f, \"Content-Type: multipart\/report;\" \" report-type=delivery-status; boundary=%s\\n\" \"MIME-Version: 1.0\\n\", bound); if ((wmf_text = next_emf(wmf, US\"header\"))) fprintf(f, \"%s\\n\", wmf_text); else fprintf(f, \"Subject: Warning: message %s delayed %s\\n\\n\", message_id, warnmsg_delay); \/* output human readable part as text\/plain section *\/ fprintf(f, \"--%s\\n\" \"Content-type: text\/plain; charset=us-ascii\\n\\n\", bound); if ((wmf_text = next_emf(wmf, US\"intro\"))) fprintf(f, \"%s\", CS wmf_text); else { fprintf(f, \"This message was created automatically by mail delivery software.\\n\"); if (Ustrcmp(recipients, sender_address) == 0) fprintf(f, \"A message that you sent has not yet been delivered to one or more of its\\n\" \"recipients after more than \"); else fprintf(f, \"A message sent by\\n\\n <%s>\\n\\n\" \"has not yet been delivered to one or more of its recipients after more than \\n\", sender_address); fprintf(f, \"%s on the queue on %s.\\n\\n\" \"The message identifier is: %s\\n\", warnmsg_delay, primary_hostname, message_id); for (h = header_list; h; h = h->next) if (strncmpic(h->text, US\"Subject:\", 8) == 0) fprintf(f, \"The subject of the message is: %s\", h->text + 9); else if (strncmpic(h->text, US\"Date:\", 5) == 0) fprintf(f, \"The date of the message is: %s\", h->text + 6); fputc('\\n', f); fprintf(f, \"The address%s to which the message has not yet been \" \"delivered %s:\\n\", !addr_defer->next ? \"\" : \"es\", !addr_defer->next ? \"is\": \"are\"); } \/* List the addresses, with error information if allowed *\/ \/* store addr_defer for machine readable part *\/ address_item *addr_dsndefer = addr_defer; fputc('\\n', f); while (addr_defer) { address_item *addr = addr_defer; addr_defer = addr->next; if (print_address_information(addr, f, US\" \", US\"\\n \", US\"\")) print_address_error(addr, f, US\"Delay reason: \"); fputc('\\n', f); } fputc('\\n', f); \/* Final text *\/ if (wmf) { if ((wmf_text = next_emf(wmf, US\"final\"))) fprintf(f, \"%s\", CS wmf_text); (void)fclose(wmf); } else { fprintf(f, \"No action is required on your part. Delivery attempts will continue for\\n\" \"some time, and this warning may be repeated at intervals if the message\\n\" \"remains undelivered. Eventually the mail delivery software will give up,\\n\" \"and when that happens, the message will be returned to you.\\n\"); } \/* output machine readable part *\/ fprintf(f, \"\\n--%s\\n\" \"Content-type: message\/delivery-status\\n\\n\" \"Reporting-MTA: dns; %s\\n\", bound, smtp_active_hostname); if (dsn_envid) { \/* must be decoded from xtext: see RFC 3461:6.3a *\/ uschar *xdec_envid; if (auth_xtextdecode(dsn_envid, &xdec_envid) > 0) fprintf(f,\"Original-Envelope-ID: %s\\n\", dsn_envid); else fprintf(f,\"X-Original-Envelope-ID: error decoding xtext formatted ENVID\\n\"); } fputc('\\n', f); for ( ; addr_dsndefer; addr_dsndefer = addr_dsndefer->next) { if (addr_dsndefer->dsn_orcpt) fprintf(f, \"Original-Recipient: %s\\n\", addr_dsndefer->dsn_orcpt); fprintf(f, \"Action: delayed\\n\" \"Final-Recipient: rfc822;%s\\n\" \"Status: 4.0.0\\n\", addr_dsndefer->address); if (addr_dsndefer->host_used && addr_dsndefer->host_used->name) { fprintf(f, \"Remote-MTA: dns; %s\\n\", addr_dsndefer->host_used->name); print_dsn_diagnostic_code(addr_dsndefer, f); } fputc('\\n', f); } fprintf(f, \"--%s\\n\" \"Content-type: text\/rfc822-headers\\n\\n\", bound); fflush(f); \/* header only as required by RFC. only failure DSN needs to honor RET=FULL *\/ tctx.u.fd = fileno(f); tctx.options = topt_add_return_path | topt_no_body; transport_filter_argv = NULL; \/* Just in case *\/ return_path = sender_address; \/* In case not previously set *\/ \/* Write the original email out *\/ \/*XXX no checking for failure! buggy! *\/ transport_write_message(&tctx, 0); fflush(f); fprintf(f,\"\\n--%s--\\n\", bound); fflush(f); \/* Close and wait for child process to complete, without a timeout. If there's an error, don't update the count. *\/ (void)fclose(f); if (child_close(pid, 0) == 0) { warning_count = count; update_spool = TRUE; \/* Ensure spool rewritten *\/ } } } } \/* Clear deliver_domain *\/ deliver_domain = NULL; \/* If this was a first delivery attempt, unset the first time flag, and ensure that the spool gets updated. *\/ if (f.deliver_firsttime) { f.deliver_firsttime = FALSE; update_spool = TRUE; } \/* If delivery was frozen and freeze_tell is set, generate an appropriate message, unless the message is a local error message (to avoid loops). Then log the freezing. If the text in \"frozen_info\" came from a system filter, it has been escaped into printing characters so as not to mess up log lines. For the \"tell\" message, we turn \\n back into newline. Also, insert a newline near the start instead of the \": \" string. *\/ if (f.deliver_freeze) { if (freeze_tell && freeze_tell[0] != 0 && !f.local_error_message) { uschar *s = string_copy(frozen_info); uschar *ss = Ustrstr(s, \" by the system filter: \"); if (ss != NULL) { ss[21] = '.'; ss[22] = '\\n'; } ss = s; while (*ss != 0) { if (*ss == '\\\\' && ss[1] == 'n') { *ss++ = ' '; *ss++ = '\\n'; } else ss++; } moan_tell_someone(freeze_tell, addr_defer, US\"Message frozen\", \"Message %s has been frozen%s.\\nThe sender is <%s>.\\n\", message_id, s, sender_address); } \/* Log freezing just before we update the -H file, to minimize the chance of a race problem. *\/ deliver_msglog(\"*** Frozen%s\\n\", frozen_info); log_write(0, LOG_MAIN, \"Frozen%s\", frozen_info); } \/* If there have been any updates to the non-recipients list, or other things that get written to the spool, we must now update the spool header file so that it has the right information for the next delivery attempt. If there was more than one address being delivered, the header_change update is done earlier, in case one succeeds and then something crashes. *\/ DEBUG(D_deliver) debug_printf(\"delivery deferred: update_spool=%d header_rewritten=%d\\n\", update_spool, f.header_rewritten); if (update_spool || f.header_rewritten) \/* Panic-dies on error *\/ (void)spool_write_header(message_id, SW_DELIVERING, NULL); } \/* Finished with the message log. If the message is complete, it will have been unlinked or renamed above. *\/ if (message_logs) (void)fclose(message_log); \/* Now we can close and remove the journal file. Its only purpose is to record successfully completed deliveries asap so that this information doesn't get lost if Exim (or the machine) crashes. Forgetting about a failed delivery is not serious, as trying it again is not harmful. The journal might not be open if all addresses were deferred at routing or directing. Nevertheless, we must remove it if it exists (may have been lying around from a crash during the previous delivery attempt). We don't remove the journal if a delivery subprocess failed to pass back delivery information; this is controlled by the remove_journal flag. When the journal is left, we also don't move the message off the main spool if frozen and the option is set. It should get moved at the next attempt, after the journal has been inspected. *\/ if (journal_fd >= 0) (void)close(journal_fd); if (remove_journal) { uschar * fname = spool_fname(US\"input\", message_subdir, id, US\"-J\"); if (Uunlink(fname) < 0 && errno != ENOENT) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"failed to unlink %s: %s\", fname, strerror(errno)); \/* Move the message off the spool if requested *\/ #ifdef SUPPORT_MOVE_FROZEN_MESSAGES if (f.deliver_freeze && move_frozen_messages) (void)spool_move_message(id, message_subdir, US\"\", US\"F\"); #endif } \/* Closing the data file frees the lock; if the file has been unlinked it will go away. Otherwise the message becomes available for another process to try delivery. *\/ (void)close(deliver_datafile); deliver_datafile = -1; DEBUG(D_deliver) debug_printf(\"end delivery of %s\\n\", id); \/* It is unlikely that there will be any cached resources, since they are released after routing, and in the delivery subprocesses. However, it's possible for an expansion for something afterwards (for example, expand_check_condition) to do a lookup. We must therefore be sure everything is released. *\/ search_tidyup(); acl_where = ACL_WHERE_UNKNOWN; return final_yield; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":60044,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) chunk[i]=(unsigned char) ReadBlobByte(image); p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if (length < 2) { if (chunk) chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (*p && ((p-chunk) < (ssize_t) length)) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 13) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 15) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 17) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":456591,"input":"qtdemux_parse_trak (GstQTDemux * qtdemux, GNode * trak) { GstByteReader tkhd; int offset; GNode *mdia; GNode *mdhd; GNode *hdlr; GNode *minf; GNode *stbl; GNode *stsd; GNode *mp4a; GNode *mp4v; GNode *wave; GNode *esds; GNode *pasp; GNode *colr; GNode *tref; GNode *udta; GNode *svmi; GNode *fiel; QtDemuxStream *stream = NULL; gboolean new_stream = FALSE; gchar *codec = NULL; const guint8 *stsd_data; guint16 lang_code; \/* quicktime lang code or packed iso code *\/ guint32 version; guint32 tkhd_flags = 0; guint8 tkhd_version = 0; guint32 fourcc; guint value_size, stsd_len, len; guint32 track_id; guint32 dummy; GST_DEBUG_OBJECT (qtdemux, \"parse_trak\"); if (!qtdemux_tree_get_child_by_type_full (trak, FOURCC_tkhd, &tkhd) || !gst_byte_reader_get_uint8 (&tkhd, &tkhd_version) || !gst_byte_reader_get_uint24_be (&tkhd, &tkhd_flags)) goto corrupt_file; \/* pick between 64 or 32 bits *\/ value_size = tkhd_version == 1 ? 8 : 4; if (!gst_byte_reader_skip (&tkhd, value_size * 2) || !gst_byte_reader_get_uint32_be (&tkhd, &track_id)) goto corrupt_file; if (!qtdemux->got_moov) { if (qtdemux_find_stream (qtdemux, track_id)) goto existing_stream; stream = _create_stream (); stream->track_id = track_id; new_stream = TRUE; } else { stream = qtdemux_find_stream (qtdemux, track_id); if (!stream) { GST_WARNING_OBJECT (qtdemux, \"Stream not found, going to ignore it\"); goto skip_track; } \/* flush samples data from this track from previous moov *\/ gst_qtdemux_stream_flush_segments_data (qtdemux, stream); gst_qtdemux_stream_flush_samples_data (qtdemux, stream); } \/* need defaults for fragments *\/ qtdemux_parse_trex (qtdemux, stream, &dummy, &dummy, &dummy); if (stream->pending_tags == NULL) stream->pending_tags = gst_tag_list_new_empty (); if ((tkhd_flags & 1) == 0) stream->disabled = TRUE; GST_LOG_OBJECT (qtdemux, \"track[tkhd] version\/flags\/id: 0x%02x\/%06x\/%u\", tkhd_version, tkhd_flags, stream->track_id); if (!(mdia = qtdemux_tree_get_child_by_type (trak, FOURCC_mdia))) goto corrupt_file; if (!(mdhd = qtdemux_tree_get_child_by_type (mdia, FOURCC_mdhd))) { \/* be nice for some crooked mjp2 files that use mhdr for mdhd *\/ if (qtdemux->major_brand != FOURCC_mjp2 || !(mdhd = qtdemux_tree_get_child_by_type (mdia, FOURCC_mhdr))) goto corrupt_file; } len = QT_UINT32 ((guint8 *) mdhd->data); version = QT_UINT32 ((guint8 *) mdhd->data + 8); GST_LOG_OBJECT (qtdemux, \"track version\/flags: %08x\", version); if (version == 0x01000000) { if (len < 38) goto corrupt_file; stream->timescale = QT_UINT32 ((guint8 *) mdhd->data + 28); stream->duration = QT_UINT64 ((guint8 *) mdhd->data + 32); lang_code = QT_UINT16 ((guint8 *) mdhd->data + 36); } else { if (len < 30) goto corrupt_file; stream->timescale = QT_UINT32 ((guint8 *) mdhd->data + 20); stream->duration = QT_UINT32 ((guint8 *) mdhd->data + 24); lang_code = QT_UINT16 ((guint8 *) mdhd->data + 28); } if (lang_code < 0x400) { qtdemux_lang_map_qt_code_to_iso (stream->lang_id, lang_code); } else if (lang_code == 0x7fff) { stream->lang_id[0] = 0; \/* unspecified *\/ } else { stream->lang_id[0] = 0x60 + ((lang_code >> 10) & 0x1F); stream->lang_id[1] = 0x60 + ((lang_code >> 5) & 0x1F); stream->lang_id[2] = 0x60 + (lang_code & 0x1F); stream->lang_id[3] = 0; } GST_LOG_OBJECT (qtdemux, \"track timescale: %\" G_GUINT32_FORMAT, stream->timescale); GST_LOG_OBJECT (qtdemux, \"track duration: %\" G_GUINT64_FORMAT, stream->duration); GST_LOG_OBJECT (qtdemux, \"track language code\/id: 0x%04x\/%s\", lang_code, stream->lang_id); if (G_UNLIKELY (stream->timescale == 0 || qtdemux->timescale == 0)) goto corrupt_file; if ((tref = qtdemux_tree_get_child_by_type (trak, FOURCC_tref))) { \/* chapters track reference *\/ GNode *chap = qtdemux_tree_get_child_by_type (tref, FOURCC_chap); if (chap) { gsize length = GST_READ_UINT32_BE (chap->data); if (qtdemux->chapters_track_id) GST_FIXME_OBJECT (qtdemux, \"Multiple CHAP tracks\"); if (length >= 12) { qtdemux->chapters_track_id = GST_READ_UINT32_BE ((gint8 *) chap->data + 8); } } } \/* fragmented files may have bogus duration in moov *\/ if (!qtdemux->fragmented && qtdemux->duration != G_MAXINT64 && stream->duration != G_MAXINT32) { guint64 tdur1, tdur2; \/* don't overflow *\/ tdur1 = stream->timescale * (guint64) qtdemux->duration; tdur2 = qtdemux->timescale * (guint64) stream->duration; \/* HACK: * some of those trailers, nowadays, have prologue images that are * themselves video tracks as well. I haven't really found a way to * identify those yet, except for just looking at their duration. *\/ if (tdur1 != 0 && (tdur2 * 10 \/ tdur1) < 2) { GST_WARNING_OBJECT (qtdemux, \"Track shorter than 20%% (%\" G_GUINT64_FORMAT \"\/%\" G_GUINT32_FORMAT \" vs. %\" G_GUINT64_FORMAT \"\/%\" G_GUINT32_FORMAT \") of the stream \" \"found, assuming preview image or something; skipping track\", stream->duration, stream->timescale, qtdemux->duration, qtdemux->timescale); if (new_stream) gst_qtdemux_stream_free (qtdemux, stream); return TRUE; } } if (!(hdlr = qtdemux_tree_get_child_by_type (mdia, FOURCC_hdlr))) goto corrupt_file; GST_LOG_OBJECT (qtdemux, \"track type: %\" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (QT_FOURCC ((guint8 *) hdlr->data + 12))); len = QT_UINT32 ((guint8 *) hdlr->data); if (len >= 20) stream->subtype = QT_FOURCC ((guint8 *) hdlr->data + 16); GST_LOG_OBJECT (qtdemux, \"track subtype: %\" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (stream->subtype)); if (!(minf = qtdemux_tree_get_child_by_type (mdia, FOURCC_minf))) goto corrupt_file; if (!(stbl = qtdemux_tree_get_child_by_type (minf, FOURCC_stbl))) goto corrupt_file; \/*parse svmi header if existing *\/ svmi = qtdemux_tree_get_child_by_type (stbl, FOURCC_svmi); if (svmi) { len = QT_UINT32 ((guint8 *) svmi->data); version = QT_UINT32 ((guint8 *) svmi->data + 8); if (!version) { GstVideoMultiviewMode mode = GST_VIDEO_MULTIVIEW_MODE_NONE; GstVideoMultiviewFlags flags = GST_VIDEO_MULTIVIEW_FLAGS_NONE; guint8 frame_type, frame_layout; \/* MPEG-A stereo video *\/ if (qtdemux->major_brand == FOURCC_ss02) flags |= GST_VIDEO_MULTIVIEW_FLAGS_MIXED_MONO; frame_type = QT_UINT8 ((guint8 *) svmi->data + 12); frame_layout = QT_UINT8 ((guint8 *) svmi->data + 13) & 0x01; switch (frame_type) { case 0: mode = GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE; break; case 1: mode = GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED; break; case 2: mode = GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME; break; case 3: \/* mode 3 is primary\/secondary view sequence, ie * left\/right views in separate tracks. See section 7.2 * of ISO\/IEC 23000-11:2009 *\/ GST_FIXME_OBJECT (qtdemux, \"Implement stereo video in separate streams\"); } if ((frame_layout & 0x1) == 0) flags |= GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST; GST_LOG_OBJECT (qtdemux, \"StereoVideo: composition type: %u, is_left_first: %u\", frame_type, frame_layout); stream->multiview_mode = mode; stream->multiview_flags = flags; } } \/* parse stsd *\/ if (!(stsd = qtdemux_tree_get_child_by_type (stbl, FOURCC_stsd))) goto corrupt_file; stsd_data = (const guint8 *) stsd->data; \/* stsd should at least have one entry *\/ stsd_len = QT_UINT32 (stsd_data); if (stsd_len < 24) { \/* .. but skip stream with empty stsd produced by some Vivotek cameras *\/ if (stream->subtype == FOURCC_vivo) { if (new_stream) gst_qtdemux_stream_free (qtdemux, stream); return TRUE; } else { goto corrupt_file; } } GST_LOG_OBJECT (qtdemux, \"stsd len: %d\", stsd_len); \/* and that entry should fit within stsd *\/ len = QT_UINT32 (stsd_data + 16); if (len > stsd_len + 16) goto corrupt_file; stream->fourcc = fourcc = QT_FOURCC (stsd_data + 16 + 4); GST_LOG_OBJECT (qtdemux, \"stsd type: %\" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (stream->fourcc)); GST_LOG_OBJECT (qtdemux, \"stsd type len: %d\", len); if ((fourcc == FOURCC_drms) || (fourcc == FOURCC_drmi)) goto error_encrypted; if (fourcc == FOURCC_encv || fourcc == FOURCC_enca) { GNode *enc = qtdemux_tree_get_child_by_type (stsd, fourcc); stream->protected = TRUE; if (!qtdemux_parse_protection_scheme_info (qtdemux, stream, enc, &fourcc)) GST_ERROR_OBJECT (qtdemux, \"Failed to parse protection scheme info\"); } if (stream->subtype == FOURCC_vide) { guint32 w = 0, h = 0; gboolean gray; gint depth, palette_size, palette_count; guint32 matrix[9]; guint32 *palette_data = NULL; stream->sampled = TRUE; \/* version 1 uses some 64-bit ints *\/ if (!gst_byte_reader_skip (&tkhd, 20 + value_size)) goto corrupt_file; if (!qtdemux_parse_transformation_matrix (qtdemux, &tkhd, matrix, \"tkhd\")) goto corrupt_file; if (!gst_byte_reader_get_uint32_be (&tkhd, &w) || !gst_byte_reader_get_uint32_be (&tkhd, &h)) goto corrupt_file; stream->display_width = w >> 16; stream->display_height = h >> 16; qtdemux_inspect_transformation_matrix (qtdemux, stream, matrix, &stream->pending_tags); offset = 16; if (len < 86) goto corrupt_file; stream->width = QT_UINT16 (stsd_data + offset + 32); stream->height = QT_UINT16 (stsd_data + offset + 34); stream->fps_n = 0; \/* this is filled in later *\/ stream->fps_d = 0; \/* this is filled in later *\/ stream->bits_per_sample = QT_UINT16 (stsd_data + offset + 82); stream->color_table_id = QT_UINT16 (stsd_data + offset + 84); \/* if color_table_id is 0, ctab atom must follow; however some files * produced by TMPEGEnc have color_table_id = 0 and no ctab atom, so * if color table is not present we'll correct the value *\/ if (stream->color_table_id == 0 && (len < 90 || QT_FOURCC (stsd_data + offset + 86) != FOURCC_ctab)) { stream->color_table_id = -1; } GST_LOG_OBJECT (qtdemux, \"width %d, height %d, bps %d, color table id %d\", stream->width, stream->height, stream->bits_per_sample, stream->color_table_id); depth = stream->bits_per_sample; \/* more than 32 bits means grayscale *\/ gray = (depth > 32); \/* low 32 bits specify the depth *\/ depth &= 0x1F; \/* different number of palette entries is determined by depth. *\/ palette_count = 0; if ((depth == 1) || (depth == 2) || (depth == 4) || (depth == 8)) palette_count = (1 << depth); palette_size = palette_count * 4; if (stream->color_table_id) { switch (palette_count) { case 0: break; case 2: palette_data = g_memdup (ff_qt_default_palette_2, palette_size); break; case 4: palette_data = g_memdup (ff_qt_default_palette_4, palette_size); break; case 16: if (gray) palette_data = g_memdup (ff_qt_grayscale_palette_16, palette_size); else palette_data = g_memdup (ff_qt_default_palette_16, palette_size); break; case 256: if (gray) palette_data = g_memdup (ff_qt_grayscale_palette_256, palette_size); else palette_data = g_memdup (ff_qt_default_palette_256, palette_size); break; default: GST_ELEMENT_WARNING (qtdemux, STREAM, DEMUX, (_(\"The video in this file might not play correctly.\")), (\"unsupported palette depth %d\", depth)); break; } } else { gint i, j, start, end; if (len < 94) goto corrupt_file; \/* read table *\/ start = QT_UINT32 (stsd_data + offset + 86); palette_count = QT_UINT16 (stsd_data + offset + 90); end = QT_UINT16 (stsd_data + offset + 92); GST_LOG_OBJECT (qtdemux, \"start %d, end %d, palette_count %d\", start, end, palette_count); if (end > 255) end = 255; if (start > end) start = end; if (len < 94 + (end - start) * 8) goto corrupt_file; \/* palette is always the same size *\/ palette_data = g_malloc0 (256 * 4); palette_size = 256 * 4; for (j = 0, i = start; i <= end; j++, i++) { guint32 a, r, g, b; a = QT_UINT16 (stsd_data + offset + 94 + (j * 8)); r = QT_UINT16 (stsd_data + offset + 96 + (j * 8)); g = QT_UINT16 (stsd_data + offset + 98 + (j * 8)); b = QT_UINT16 (stsd_data + offset + 100 + (j * 8)); palette_data[i] = ((a & 0xff00) << 16) | ((r & 0xff00) << 8) | (g & 0xff00) | (b >> 8); } } if (stream->caps) gst_caps_unref (stream->caps); stream->caps = qtdemux_video_caps (qtdemux, stream, fourcc, stsd_data, &codec); if (G_UNLIKELY (!stream->caps)) { g_free (palette_data); goto unknown_stream; } if (codec) { gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_VIDEO_CODEC, codec, NULL); g_free (codec); codec = NULL; } if (palette_data) { GstStructure *s; if (stream->rgb8_palette) gst_memory_unref (stream->rgb8_palette); stream->rgb8_palette = gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY, palette_data, palette_size, 0, palette_size, palette_data, g_free); s = gst_caps_get_structure (stream->caps, 0); \/* non-raw video has a palette_data property. raw video has the palette as * an extra plane that we append to the output buffers before we push * them*\/ if (!gst_structure_has_name (s, \"video\/x-raw\")) { GstBuffer *palette; palette = gst_buffer_new (); gst_buffer_append_memory (palette, stream->rgb8_palette); stream->rgb8_palette = NULL; gst_caps_set_simple (stream->caps, \"palette_data\", GST_TYPE_BUFFER, palette, NULL); gst_buffer_unref (palette); } } else if (palette_count != 0) { GST_ELEMENT_WARNING (qtdemux, STREAM, NOT_IMPLEMENTED, (NULL), (\"Unsupported palette depth %d\", depth)); } GST_LOG_OBJECT (qtdemux, \"frame count: %u\", QT_UINT16 (stsd_data + offset + 48)); esds = NULL; pasp = NULL; colr = NULL; fiel = NULL; \/* pick 'the' stsd child *\/ if (!stream->protected) mp4v = qtdemux_tree_get_child_by_type (stsd, fourcc); else mp4v = qtdemux_tree_get_child_by_type (stsd, FOURCC_encv); if (mp4v) { esds = qtdemux_tree_get_child_by_type (mp4v, FOURCC_esds); pasp = qtdemux_tree_get_child_by_type (mp4v, FOURCC_pasp); colr = qtdemux_tree_get_child_by_type (mp4v, FOURCC_colr); fiel = qtdemux_tree_get_child_by_type (mp4v, FOURCC_fiel); } if (pasp) { const guint8 *pasp_data = (const guint8 *) pasp->data; stream->par_w = QT_UINT32 (pasp_data + 8); stream->par_h = QT_UINT32 (pasp_data + 12); } else { stream->par_w = 0; stream->par_h = 0; } if (fiel) { const guint8 *fiel_data = (const guint8 *) fiel->data; gint len = QT_UINT32 (fiel_data); if (len == 10) { stream->interlace_mode = GST_READ_UINT8 (fiel_data + 8); stream->field_order = GST_READ_UINT8 (fiel_data + 9); } } if (colr) { const guint8 *colr_data = (const guint8 *) colr->data; gint len = QT_UINT32 (colr_data); if (len == 19 || len == 18) { guint32 color_type = GST_READ_UINT32_LE (colr_data + 8); if (color_type == FOURCC_nclx || color_type == FOURCC_nclc) { guint16 primaries = GST_READ_UINT16_BE (colr_data + 12); guint16 transfer_function = GST_READ_UINT16_BE (colr_data + 14); guint16 matrix = GST_READ_UINT16_BE (colr_data + 16); gboolean full_range = len == 19 ? colr_data[17] >> 7 : FALSE; switch (primaries) { case 1: stream->colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_BT709; break; case 5: stream->colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_BT470BG; break; case 6: stream->colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_SMPTE170M; break; case 9: stream->colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_BT2020; break; default: break; } switch (transfer_function) { case 1: stream->colorimetry.transfer = GST_VIDEO_TRANSFER_BT709; break; case 7: stream->colorimetry.transfer = GST_VIDEO_TRANSFER_SMPTE240M; break; default: break; } switch (matrix) { case 1: stream->colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_BT709; break; case 6: stream->colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_BT601; break; case 7: stream->colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_SMPTE240M; break; case 9: stream->colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_BT2020; break; default: break; } stream->colorimetry.range = full_range ? GST_VIDEO_COLOR_RANGE_0_255 : GST_VIDEO_COLOR_RANGE_16_235; } else { GST_DEBUG_OBJECT (qtdemux, \"Unsupported color type\"); } } else { GST_WARNING_OBJECT (qtdemux, \"Invalid colr atom size\"); } } if (esds) { gst_qtdemux_handle_esds (qtdemux, stream, esds, stream->pending_tags); } else { switch (fourcc) { case FOURCC_H264: case FOURCC_avc1: case FOURCC_avc3: { gint len = QT_UINT32 (stsd_data) - 0x66; const guint8 *avc_data = stsd_data + 0x66; \/* find avcC *\/ while (len >= 0x8) { gint size; if (QT_UINT32 (avc_data) <= len) size = QT_UINT32 (avc_data) - 0x8; else size = len - 0x8; if (size < 1) \/* No real data, so break out *\/ break; switch (QT_FOURCC (avc_data + 0x4)) { case FOURCC_avcC: { \/* parse, if found *\/ GstBuffer *buf; GST_DEBUG_OBJECT (qtdemux, \"found avcC codec_data in stsd\"); \/* First 4 bytes are the length of the atom, the next 4 bytes * are the fourcc, the next 1 byte is the version, and the * subsequent bytes are profile_tier_level structure like data. *\/ gst_codec_utils_h264_caps_set_level_and_profile (stream->caps, avc_data + 8 + 1, size - 1); buf = gst_buffer_new_and_alloc (size); gst_buffer_fill (buf, 0, avc_data + 0x8, size); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); break; } case FOURCC_strf: { GstBuffer *buf; GST_DEBUG_OBJECT (qtdemux, \"found strf codec_data in stsd\"); \/* First 4 bytes are the length of the atom, the next 4 bytes * are the fourcc, next 40 bytes are BITMAPINFOHEADER, * next 1 byte is the version, and the * subsequent bytes are sequence parameter set like data. *\/ size -= 40; \/* we'll be skipping BITMAPINFOHEADER *\/ if (size > 1) { gst_codec_utils_h264_caps_set_level_and_profile (stream->caps, avc_data + 8 + 40 + 1, size - 1); buf = gst_buffer_new_and_alloc (size); gst_buffer_fill (buf, 0, avc_data + 8 + 40, size); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); } break; } case FOURCC_btrt: { guint avg_bitrate, max_bitrate; \/* bufferSizeDB, maxBitrate and avgBitrate - 4 bytes each *\/ if (size < 12) break; max_bitrate = QT_UINT32 (avc_data + 0xc); avg_bitrate = QT_UINT32 (avc_data + 0x10); if (!max_bitrate && !avg_bitrate) break; \/* Some muxers seem to swap the average and maximum bitrates * (I'm looking at you, YouTube), so we swap for sanity. *\/ if (max_bitrate > 0 && max_bitrate < avg_bitrate) { guint temp = avg_bitrate; avg_bitrate = max_bitrate; max_bitrate = temp; } if (max_bitrate > 0 && max_bitrate < G_MAXUINT32) { gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_MAXIMUM_BITRATE, max_bitrate, NULL); } if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32) { gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE, avg_bitrate, NULL); } break; } default: break; } len -= size + 8; avc_data += size + 8; } break; } case FOURCC_H265: case FOURCC_hvc1: case FOURCC_hev1: { gint len = QT_UINT32 (stsd_data) - 0x66; const guint8 *hevc_data = stsd_data + 0x66; \/* find hevc *\/ while (len >= 0x8) { gint size; if (QT_UINT32 (hevc_data) <= len) size = QT_UINT32 (hevc_data) - 0x8; else size = len - 0x8; if (size < 1) \/* No real data, so break out *\/ break; switch (QT_FOURCC (hevc_data + 0x4)) { case FOURCC_hvcC: { \/* parse, if found *\/ GstBuffer *buf; GST_DEBUG_OBJECT (qtdemux, \"found avcC codec_data in stsd\"); \/* First 4 bytes are the length of the atom, the next 4 bytes * are the fourcc, the next 1 byte is the version, and the * subsequent bytes are sequence parameter set like data. *\/ gst_codec_utils_h265_caps_set_level_tier_and_profile (stream->caps, hevc_data + 8 + 1, size - 1); buf = gst_buffer_new_and_alloc (size); gst_buffer_fill (buf, 0, hevc_data + 0x8, size); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); break; } default: break; } len -= size + 8; hevc_data += size + 8; } break; } case FOURCC_mp4v: case FOURCC_MP4V: case FOURCC_fmp4: case FOURCC_FMP4: { GNode *glbl; GST_DEBUG_OBJECT (qtdemux, \"found %\" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc)); \/* codec data might be in glbl extension atom *\/ glbl = mp4v ? qtdemux_tree_get_child_by_type (mp4v, FOURCC_glbl) : NULL; if (glbl) { guint8 *data; GstBuffer *buf; gint len; GST_DEBUG_OBJECT (qtdemux, \"found glbl data in stsd\"); data = glbl->data; len = QT_UINT32 (data); if (len > 0x8) { len -= 0x8; buf = gst_buffer_new_and_alloc (len); gst_buffer_fill (buf, 0, data + 8, len); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); } } break; } case FOURCC_mjp2: { \/* see annex I of the jpeg2000 spec *\/ GNode *jp2h, *ihdr, *colr, *mjp2, *field, *prefix, *cmap, *cdef; const guint8 *data; const gchar *colorspace = NULL; gint ncomp = 0; guint32 ncomp_map = 0; gint32 *comp_map = NULL; guint32 nchan_def = 0; gint32 *chan_def = NULL; GST_DEBUG_OBJECT (qtdemux, \"found mjp2\"); \/* some required atoms *\/ mjp2 = qtdemux_tree_get_child_by_type (stsd, FOURCC_mjp2); if (!mjp2) break; jp2h = qtdemux_tree_get_child_by_type (mjp2, FOURCC_jp2h); if (!jp2h) break; \/* number of components; redundant with info in codestream, but useful to a muxer *\/ ihdr = qtdemux_tree_get_child_by_type (jp2h, FOURCC_ihdr); if (!ihdr || QT_UINT32 (ihdr->data) != 22) break; ncomp = QT_UINT16 (((guint8 *) ihdr->data) + 16); colr = qtdemux_tree_get_child_by_type (jp2h, FOURCC_colr); if (!colr) break; GST_DEBUG_OBJECT (qtdemux, \"found colr\"); \/* extract colour space info *\/ if (QT_UINT8 ((guint8 *) colr->data + 8) == 1) { switch (QT_UINT32 ((guint8 *) colr->data + 11)) { case 16: colorspace = \"sRGB\"; break; case 17: colorspace = \"GRAY\"; break; case 18: colorspace = \"sYUV\"; break; default: colorspace = NULL; break; } } if (!colorspace) \/* colr is required, and only values 16, 17, and 18 are specified, so error if we have no colorspace *\/ break; \/* extract component mapping *\/ cmap = qtdemux_tree_get_child_by_type (jp2h, FOURCC_cmap); if (cmap) { guint32 cmap_len = 0; int i; cmap_len = QT_UINT32 (cmap->data); if (cmap_len >= 8) { \/* normal box, subtract off header *\/ cmap_len -= 8; \/* cmap: { u16 cmp; u8 mtyp; u8 pcol; }* *\/ if (cmap_len % 4 == 0) { ncomp_map = (cmap_len \/ 4); comp_map = g_new0 (gint32, ncomp_map); for (i = 0; i < ncomp_map; i++) { guint16 cmp; guint8 mtyp, pcol; cmp = QT_UINT16 (((guint8 *) cmap->data) + 8 + i * 4); mtyp = QT_UINT8 (((guint8 *) cmap->data) + 8 + i * 4 + 2); pcol = QT_UINT8 (((guint8 *) cmap->data) + 8 + i * 4 + 3); comp_map[i] = (mtyp << 24) | (pcol << 16) | cmp; } } } } \/* extract channel definitions *\/ cdef = qtdemux_tree_get_child_by_type (jp2h, FOURCC_cdef); if (cdef) { guint32 cdef_len = 0; int i; cdef_len = QT_UINT32 (cdef->data); if (cdef_len >= 10) { \/* normal box, subtract off header and len *\/ cdef_len -= 10; \/* cdef: u16 n; { u16 cn; u16 typ; u16 asoc; }* *\/ if (cdef_len % 6 == 0) { nchan_def = (cdef_len \/ 6); chan_def = g_new0 (gint32, nchan_def); for (i = 0; i < nchan_def; i++) chan_def[i] = -1; for (i = 0; i < nchan_def; i++) { guint16 cn, typ, asoc; cn = QT_UINT16 (((guint8 *) cdef->data) + 10 + i * 6); typ = QT_UINT16 (((guint8 *) cdef->data) + 10 + i * 6 + 2); asoc = QT_UINT16 (((guint8 *) cdef->data) + 10 + i * 6 + 4); if (cn < nchan_def) { switch (typ) { case 0: chan_def[cn] = asoc; break; case 1: chan_def[cn] = 0; \/* alpha *\/ break; default: chan_def[cn] = -typ; } } } } } } gst_caps_set_simple (stream->caps, \"num-components\", G_TYPE_INT, ncomp, NULL); gst_caps_set_simple (stream->caps, \"colorspace\", G_TYPE_STRING, colorspace, NULL); if (comp_map) { GValue arr = { 0, }; GValue elt = { 0, }; int i; g_value_init (&arr, GST_TYPE_ARRAY); g_value_init (&elt, G_TYPE_INT); for (i = 0; i < ncomp_map; i++) { g_value_set_int (&elt, comp_map[i]); gst_value_array_append_value (&arr, &elt); } gst_structure_set_value (gst_caps_get_structure (stream->caps, 0), \"component-map\", &arr); g_value_unset (&elt); g_value_unset (&arr); g_free (comp_map); } if (chan_def) { GValue arr = { 0, }; GValue elt = { 0, }; int i; g_value_init (&arr, GST_TYPE_ARRAY); g_value_init (&elt, G_TYPE_INT); for (i = 0; i < nchan_def; i++) { g_value_set_int (&elt, chan_def[i]); gst_value_array_append_value (&arr, &elt); } gst_structure_set_value (gst_caps_get_structure (stream->caps, 0), \"channel-definitions\", &arr); g_value_unset (&elt); g_value_unset (&arr); g_free (chan_def); } \/* some optional atoms *\/ field = qtdemux_tree_get_child_by_type (mjp2, FOURCC_fiel); prefix = qtdemux_tree_get_child_by_type (mjp2, FOURCC_jp2x); \/* indicate possible fields in caps *\/ if (field) { data = (guint8 *) field->data + 8; if (*data != 1) gst_caps_set_simple (stream->caps, \"fields\", G_TYPE_INT, (gint) * data, NULL); } \/* add codec_data if provided *\/ if (prefix) { GstBuffer *buf; gint len; GST_DEBUG_OBJECT (qtdemux, \"found prefix data in stsd\"); data = prefix->data; len = QT_UINT32 (data); if (len > 0x8) { len -= 0x8; buf = gst_buffer_new_and_alloc (len); gst_buffer_fill (buf, 0, data + 8, len); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); } } break; } case FOURCC_jpeg: { \/* https:\/\/developer.apple.com\/standards\/qtff-2001.pdf, * page 92, \"Video Sample Description\", under table 3.1 *\/ GstByteReader br; const gint compressor_offset = 16 + 4 + 4 * 3 + 2 * 2 + 2 * 4 + 4 + 2; const gint min_size = compressor_offset + 32 + 2 + 2; GNode *jpeg; guint32 len; guint16 color_table_id = 0; gboolean ok; GST_DEBUG_OBJECT (qtdemux, \"found jpeg\"); \/* recover information on interlaced\/progressive *\/ jpeg = qtdemux_tree_get_child_by_type (stsd, FOURCC_jpeg); if (!jpeg) break; len = QT_UINT32 (jpeg->data); GST_DEBUG_OBJECT (qtdemux, \"Found jpeg: len %u, need %d\", len, min_size); if (len >= min_size) { gst_byte_reader_init (&br, jpeg->data, len); gst_byte_reader_skip (&br, compressor_offset + 32 + 2); gst_byte_reader_get_uint16_le (&br, &color_table_id); if (color_table_id != 0) { \/* the spec says there can be concatenated chunks in the data, and we want * to find one called field. Walk through them. *\/ gint offset = min_size; while (offset + 8 < len) { guint32 size = 0, tag; ok = gst_byte_reader_get_uint32_le (&br, &size); ok &= gst_byte_reader_get_uint32_le (&br, &tag); if (!ok || size < 8) { GST_WARNING_OBJECT (qtdemux, \"Failed to walk optional chunk list\"); break; } GST_DEBUG_OBJECT (qtdemux, \"Found optional %4.4s chunk, size %u\", (const char *) &tag, size); if (tag == FOURCC_fiel) { guint8 n_fields, ordering; gst_byte_reader_get_uint8 (&br, &n_fields); gst_byte_reader_get_uint8 (&br, &ordering); if (n_fields == 1 || n_fields == 2) { GST_DEBUG_OBJECT (qtdemux, \"Found fiel tag with %u fields, ordering %u\", n_fields, ordering); if (n_fields == 2) gst_caps_set_simple (stream->caps, \"interlace-mode\", G_TYPE_STRING, \"interleaved\", NULL); } else { GST_WARNING_OBJECT (qtdemux, \"Found fiel tag with invalid fields (%u)\", n_fields); } } offset += size; } } else { GST_DEBUG_OBJECT (qtdemux, \"Color table ID is 0, not trying to get interlacedness\"); } } else { GST_WARNING_OBJECT (qtdemux, \"Length of jpeg chunk is too small, not trying to get interlacedness\"); } break; } case FOURCC_SVQ3: case FOURCC_VP31: { GstBuffer *buf; GstBuffer *seqh = NULL; guint8 *gamma_data = NULL; gint len = QT_UINT32 (stsd_data); qtdemux_parse_svq3_stsd_data (qtdemux, stsd, &gamma_data, &seqh); if (gamma_data) { gst_caps_set_simple (stream->caps, \"applied-gamma\", G_TYPE_DOUBLE, QT_FP32 (gamma_data), NULL); } if (seqh) { \/* sorry for the bad name, but we don't know what this is, other * than its own fourcc *\/ gst_caps_set_simple (stream->caps, \"seqh\", GST_TYPE_BUFFER, seqh, NULL); } GST_DEBUG_OBJECT (qtdemux, \"found codec_data in stsd\"); buf = gst_buffer_new_and_alloc (len); gst_buffer_fill (buf, 0, stsd_data, len); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); break; } case FOURCC_rle_: case FOURCC_WRLE: { gst_caps_set_simple (stream->caps, \"depth\", G_TYPE_INT, QT_UINT16 (stsd_data + offset + 82), NULL); break; } case FOURCC_XiTh: { GNode *xith, *xdxt; GST_DEBUG_OBJECT (qtdemux, \"found XiTh\"); xith = qtdemux_tree_get_child_by_type (stsd, FOURCC_XiTh); if (!xith) break; xdxt = qtdemux_tree_get_child_by_type (xith, FOURCC_XdxT); if (!xdxt) break; GST_DEBUG_OBJECT (qtdemux, \"found XdxT node\"); \/* collect the headers and store them in a stream list so that we can * send them out first *\/ qtdemux_parse_theora_extension (qtdemux, stream, xdxt); break; } case FOURCC_ovc1: { GNode *ovc1; guint8 *ovc1_data; guint ovc1_len; GstBuffer *buf; GST_DEBUG_OBJECT (qtdemux, \"parse ovc1 header\"); ovc1 = qtdemux_tree_get_child_by_type (stsd, FOURCC_ovc1); if (!ovc1) break; ovc1_data = ovc1->data; ovc1_len = QT_UINT32 (ovc1_data); if (ovc1_len <= 198) { GST_WARNING_OBJECT (qtdemux, \"Too small ovc1 header, skipping\"); break; } buf = gst_buffer_new_and_alloc (ovc1_len - 198); gst_buffer_fill (buf, 0, ovc1_data + 198, ovc1_len - 198); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); break; } case FOURCC_vc_1: { gint len = QT_UINT32 (stsd_data) - 0x66; const guint8 *vc1_data = stsd_data + 0x66; \/* find dvc1 *\/ while (len >= 8) { gint size; if (QT_UINT32 (vc1_data) <= len) size = QT_UINT32 (vc1_data) - 8; else size = len - 8; if (size < 1) \/* No real data, so break out *\/ break; switch (QT_FOURCC (vc1_data + 0x4)) { case GST_MAKE_FOURCC ('d', 'v', 'c', '1'): { GstBuffer *buf; GST_DEBUG_OBJECT (qtdemux, \"found dvc1 codec_data in stsd\"); buf = gst_buffer_new_and_alloc (size); gst_buffer_fill (buf, 0, vc1_data + 8, size); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); break; } default: break; } len -= size + 8; vc1_data += size + 8; } break; } default: break; } } GST_INFO_OBJECT (qtdemux, \"type %\" GST_FOURCC_FORMAT \" caps %\" GST_PTR_FORMAT, GST_FOURCC_ARGS (fourcc), stream->caps); } else if (stream->subtype == FOURCC_soun) { int version, samplesize; guint16 compression_id; gboolean amrwb = FALSE; offset = 32; \/* sample description entry (16) + sound sample description v0 (20) *\/ if (len < 36) goto corrupt_file; version = QT_UINT32 (stsd_data + offset); stream->n_channels = QT_UINT16 (stsd_data + offset + 8); samplesize = QT_UINT16 (stsd_data + offset + 10); compression_id = QT_UINT16 (stsd_data + offset + 12); stream->rate = QT_FP32 (stsd_data + offset + 16); GST_LOG_OBJECT (qtdemux, \"version\/rev: %08x\", version); GST_LOG_OBJECT (qtdemux, \"vendor: %08x\", QT_UINT32 (stsd_data + offset + 4)); GST_LOG_OBJECT (qtdemux, \"n_channels: %d\", stream->n_channels); GST_LOG_OBJECT (qtdemux, \"sample_size: %d\", samplesize); GST_LOG_OBJECT (qtdemux, \"compression_id: %d\", compression_id); GST_LOG_OBJECT (qtdemux, \"packet size: %d\", QT_UINT16 (stsd_data + offset + 14)); GST_LOG_OBJECT (qtdemux, \"sample rate: %g\", stream->rate); if (compression_id == 0xfffe) stream->sampled = TRUE; \/* first assume uncompressed audio *\/ stream->bytes_per_sample = samplesize \/ 8; stream->samples_per_frame = stream->n_channels; stream->bytes_per_frame = stream->n_channels * stream->bytes_per_sample; stream->samples_per_packet = stream->samples_per_frame; stream->bytes_per_packet = stream->bytes_per_sample; offset = 52; switch (fourcc) { \/* Yes, these have to be hard-coded *\/ case FOURCC_MAC6: { stream->samples_per_packet = 6; stream->bytes_per_packet = 1; stream->bytes_per_frame = 1 * stream->n_channels; stream->bytes_per_sample = 1; stream->samples_per_frame = 6 * stream->n_channels; break; } case FOURCC_MAC3: { stream->samples_per_packet = 3; stream->bytes_per_packet = 1; stream->bytes_per_frame = 1 * stream->n_channels; stream->bytes_per_sample = 1; stream->samples_per_frame = 3 * stream->n_channels; break; } case FOURCC_ima4: { stream->samples_per_packet = 64; stream->bytes_per_packet = 34; stream->bytes_per_frame = 34 * stream->n_channels; stream->bytes_per_sample = 2; stream->samples_per_frame = 64 * stream->n_channels; break; } case FOURCC_ulaw: case FOURCC_alaw: { stream->samples_per_packet = 1; stream->bytes_per_packet = 1; stream->bytes_per_frame = 1 * stream->n_channels; stream->bytes_per_sample = 1; stream->samples_per_frame = 1 * stream->n_channels; break; } case FOURCC_agsm: { stream->samples_per_packet = 160; stream->bytes_per_packet = 33; stream->bytes_per_frame = 33 * stream->n_channels; stream->bytes_per_sample = 2; stream->samples_per_frame = 160 * stream->n_channels; break; } default: break; } if (version == 0x00010000) { \/* sample description entry (16) + sound sample description v1 (20+16) *\/ if (len < 52) goto corrupt_file; switch (fourcc) { case FOURCC_twos: case FOURCC_sowt: case FOURCC_raw_: break; default: { \/* only parse extra decoding config for non-pcm audio *\/ stream->samples_per_packet = QT_UINT32 (stsd_data + offset); stream->bytes_per_packet = QT_UINT32 (stsd_data + offset + 4); stream->bytes_per_frame = QT_UINT32 (stsd_data + offset + 8); stream->bytes_per_sample = QT_UINT32 (stsd_data + offset + 12); GST_LOG_OBJECT (qtdemux, \"samples\/packet: %d\", stream->samples_per_packet); GST_LOG_OBJECT (qtdemux, \"bytes\/packet: %d\", stream->bytes_per_packet); GST_LOG_OBJECT (qtdemux, \"bytes\/frame: %d\", stream->bytes_per_frame); GST_LOG_OBJECT (qtdemux, \"bytes\/sample: %d\", stream->bytes_per_sample); if (!stream->sampled && stream->bytes_per_packet) { stream->samples_per_frame = (stream->bytes_per_frame \/ stream->bytes_per_packet) * stream->samples_per_packet; GST_LOG_OBJECT (qtdemux, \"samples\/frame: %d\", stream->samples_per_frame); } break; } } } else if (version == 0x00020000) { union { gdouble fp; guint64 val; } qtfp; \/* sample description entry (16) + sound sample description v2 (56) *\/ if (len < 72) goto corrupt_file; qtfp.val = QT_UINT64 (stsd_data + offset + 4); stream->rate = qtfp.fp; stream->n_channels = QT_UINT32 (stsd_data + offset + 12); GST_LOG_OBJECT (qtdemux, \"Sound sample description Version 2\"); GST_LOG_OBJECT (qtdemux, \"sample rate: %g\", stream->rate); GST_LOG_OBJECT (qtdemux, \"n_channels: %d\", stream->n_channels); GST_LOG_OBJECT (qtdemux, \"bits\/channel: %d\", QT_UINT32 (stsd_data + offset + 20)); GST_LOG_OBJECT (qtdemux, \"format flags: %X\", QT_UINT32 (stsd_data + offset + 24)); GST_LOG_OBJECT (qtdemux, \"bytes\/packet: %d\", QT_UINT32 (stsd_data + offset + 28)); GST_LOG_OBJECT (qtdemux, \"LPCM frames\/packet: %d\", QT_UINT32 (stsd_data + offset + 32)); } else if (version != 0x00000) { GST_WARNING_OBJECT (qtdemux, \"unknown audio STSD version %08x\", version); } if (stream->caps) gst_caps_unref (stream->caps); stream->caps = qtdemux_audio_caps (qtdemux, stream, fourcc, stsd_data + 32, len - 16, &codec); switch (fourcc) { case FOURCC_in24: { GNode *enda; GNode *in24; in24 = qtdemux_tree_get_child_by_type (stsd, FOURCC_in24); enda = qtdemux_tree_get_child_by_type (in24, FOURCC_enda); if (!enda) { wave = qtdemux_tree_get_child_by_type (in24, FOURCC_wave); if (wave) enda = qtdemux_tree_get_child_by_type (wave, FOURCC_enda); } if (enda) { int enda_value = QT_UINT16 ((guint8 *) enda->data + 8); gst_caps_set_simple (stream->caps, \"format\", G_TYPE_STRING, (enda_value) ? \"S24LE\" : \"S24BE\", NULL); } break; } case FOURCC_owma: { GNode *owma; const guint8 *owma_data; const gchar *codec_name = NULL; guint owma_len; GstBuffer *buf; gint version = 1; \/* from http:\/\/msdn.microsoft.com\/en-us\/library\/dd757720(VS.85).aspx *\/ \/* FIXME this should also be gst_riff_strf_auds, * but the latter one is actually missing bits-per-sample :( *\/ typedef struct { gint16 wFormatTag; gint16 nChannels; gint32 nSamplesPerSec; gint32 nAvgBytesPerSec; gint16 nBlockAlign; gint16 wBitsPerSample; gint16 cbSize; } WAVEFORMATEX; WAVEFORMATEX *wfex; GST_DEBUG_OBJECT (qtdemux, \"parse owma\"); owma = qtdemux_tree_get_child_by_type (stsd, FOURCC_owma); if (!owma) break; owma_data = owma->data; owma_len = QT_UINT32 (owma_data); if (owma_len <= 54) { GST_WARNING_OBJECT (qtdemux, \"Too small owma header, skipping\"); break; } wfex = (WAVEFORMATEX *) (owma_data + 36); buf = gst_buffer_new_and_alloc (owma_len - 54); gst_buffer_fill (buf, 0, owma_data + 54, owma_len - 54); if (wfex->wFormatTag == 0x0161) { codec_name = \"Windows Media Audio\"; version = 2; } else if (wfex->wFormatTag == 0x0162) { codec_name = \"Windows Media Audio 9 Pro\"; version = 3; } else if (wfex->wFormatTag == 0x0163) { codec_name = \"Windows Media Audio 9 Lossless\"; \/* is that correct? gstffmpegcodecmap.c is missing it, but * fluendo codec seems to support it *\/ version = 4; } gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, \"wmaversion\", G_TYPE_INT, version, \"block_align\", G_TYPE_INT, GST_READ_UINT16_LE (&wfex->nBlockAlign), \"bitrate\", G_TYPE_INT, GST_READ_UINT32_LE (&wfex->nAvgBytesPerSec), \"width\", G_TYPE_INT, GST_READ_UINT16_LE (&wfex->wBitsPerSample), \"depth\", G_TYPE_INT, GST_READ_UINT16_LE (&wfex->wBitsPerSample), NULL); gst_buffer_unref (buf); if (codec_name) { g_free (codec); codec = g_strdup (codec_name); } break; } case FOURCC_wma_: { gint len = QT_UINT32 (stsd_data) - offset; const guint8 *wfex_data = stsd_data + offset; const gchar *codec_name = NULL; gint version = 1; \/* from http:\/\/msdn.microsoft.com\/en-us\/library\/dd757720(VS.85).aspx *\/ \/* FIXME this should also be gst_riff_strf_auds, * but the latter one is actually missing bits-per-sample :( *\/ typedef struct { gint16 wFormatTag; gint16 nChannels; gint32 nSamplesPerSec; gint32 nAvgBytesPerSec; gint16 nBlockAlign; gint16 wBitsPerSample; gint16 cbSize; } WAVEFORMATEX; WAVEFORMATEX wfex; \/* FIXME: unify with similar wavformatex parsing code above *\/ GST_DEBUG_OBJECT (qtdemux, \"parse wma, looking for wfex\"); \/* find wfex *\/ while (len >= 8) { gint size; if (QT_UINT32 (wfex_data) <= len) size = QT_UINT32 (wfex_data) - 8; else size = len - 8; if (size < 1) \/* No real data, so break out *\/ break; switch (QT_FOURCC (wfex_data + 4)) { case GST_MAKE_FOURCC ('w', 'f', 'e', 'x'): { GST_DEBUG_OBJECT (qtdemux, \"found wfex in stsd\"); if (size < 8 + 18) break; wfex.wFormatTag = GST_READ_UINT16_LE (wfex_data + 8 + 0); wfex.nChannels = GST_READ_UINT16_LE (wfex_data + 8 + 2); wfex.nSamplesPerSec = GST_READ_UINT32_LE (wfex_data + 8 + 4); wfex.nAvgBytesPerSec = GST_READ_UINT32_LE (wfex_data + 8 + 8); wfex.nBlockAlign = GST_READ_UINT16_LE (wfex_data + 8 + 12); wfex.wBitsPerSample = GST_READ_UINT16_LE (wfex_data + 8 + 14); wfex.cbSize = GST_READ_UINT16_LE (wfex_data + 8 + 16); GST_LOG_OBJECT (qtdemux, \"Found wfex box in stsd:\"); GST_LOG_OBJECT (qtdemux, \"FormatTag = 0x%04x, Channels = %u, \" \"SamplesPerSec = %u, AvgBytesPerSec = %u, BlockAlign = %u, \" \"BitsPerSample = %u, Size = %u\", wfex.wFormatTag, wfex.nChannels, wfex.nSamplesPerSec, wfex.nAvgBytesPerSec, wfex.nBlockAlign, wfex.wBitsPerSample, wfex.cbSize); if (wfex.wFormatTag == 0x0161) { codec_name = \"Windows Media Audio\"; version = 2; } else if (wfex.wFormatTag == 0x0162) { codec_name = \"Windows Media Audio 9 Pro\"; version = 3; } else if (wfex.wFormatTag == 0x0163) { codec_name = \"Windows Media Audio 9 Lossless\"; \/* is that correct? gstffmpegcodecmap.c is missing it, but * fluendo codec seems to support it *\/ version = 4; } gst_caps_set_simple (stream->caps, \"wmaversion\", G_TYPE_INT, version, \"block_align\", G_TYPE_INT, wfex.nBlockAlign, \"bitrate\", G_TYPE_INT, wfex.nAvgBytesPerSec, \"width\", G_TYPE_INT, wfex.wBitsPerSample, \"depth\", G_TYPE_INT, wfex.wBitsPerSample, NULL); if (size > wfex.cbSize) { GstBuffer *buf; buf = gst_buffer_new_and_alloc (size - wfex.cbSize); gst_buffer_fill (buf, 0, wfex_data + 8 + wfex.cbSize, size - wfex.cbSize); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); } else { GST_WARNING_OBJECT (qtdemux, \"no codec data\"); } if (codec_name) { g_free (codec); codec = g_strdup (codec_name); } break; } default: break; } len -= size + 8; wfex_data += size + 8; } break; } case FOURCC_opus: { GNode *opus; const guint8 *opus_data; guint8 *channel_mapping = NULL; guint32 rate; guint8 channels; guint8 channel_mapping_family; guint8 stream_count; guint8 coupled_count; guint8 i; opus = qtdemux_tree_get_child_by_type (stsd, FOURCC_opus); opus_data = opus->data; channels = GST_READ_UINT8 (opus_data + 45); rate = GST_READ_UINT32_LE (opus_data + 48); channel_mapping_family = GST_READ_UINT8 (opus_data + 54); stream_count = GST_READ_UINT8 (opus_data + 55); coupled_count = GST_READ_UINT8 (opus_data + 56); if (channels > 0) { channel_mapping = g_malloc (channels * sizeof (guint8)); for (i = 0; i < channels; i++) channel_mapping[i] = GST_READ_UINT8 (opus_data + i + 57); } stream->caps = gst_codec_utils_opus_create_caps (rate, channels, channel_mapping_family, stream_count, coupled_count, channel_mapping); break; } default: break; } if (codec) { GstStructure *s; gint bitrate = 0; gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_AUDIO_CODEC, codec, NULL); g_free (codec); codec = NULL; \/* some bitrate info may have ended up in caps *\/ s = gst_caps_get_structure (stream->caps, 0); gst_structure_get_int (s, \"bitrate\", &bitrate); if (bitrate > 0) gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE, bitrate, NULL); } if (stream->protected && fourcc == FOURCC_mp4a) mp4a = qtdemux_tree_get_child_by_type (stsd, FOURCC_enca); else mp4a = qtdemux_tree_get_child_by_type (stsd, FOURCC_mp4a); wave = NULL; esds = NULL; if (mp4a) { wave = qtdemux_tree_get_child_by_type (mp4a, FOURCC_wave); if (wave) esds = qtdemux_tree_get_child_by_type (wave, FOURCC_esds); if (!esds) esds = qtdemux_tree_get_child_by_type (mp4a, FOURCC_esds); } \/* If the fourcc's bottom 16 bits gives 'sm', then the top 16 bits is a byte-swapped wave-style codec identifier, and we can find a WAVE header internally to a 'wave' atom here. This can more clearly be thought of as 'ms' as the top 16 bits, and a codec id as the bottom 16 bits - but byte-swapped to store in QT (which is big-endian). *\/ if ((fourcc & 0xffff) == (('s' << 8) | 'm')) { if (len < offset + 20) { GST_WARNING_OBJECT (qtdemux, \"No wave atom in MS-style audio\"); } else { guint32 datalen = QT_UINT32 (stsd_data + offset + 16); const guint8 *data = stsd_data + offset + 16; GNode *wavenode; GNode *waveheadernode; wavenode = g_node_new ((guint8 *) data); if (qtdemux_parse_node (qtdemux, wavenode, data, datalen)) { const guint8 *waveheader; guint32 headerlen; waveheadernode = qtdemux_tree_get_child_by_type (wavenode, fourcc); if (waveheadernode) { waveheader = (const guint8 *) waveheadernode->data; headerlen = QT_UINT32 (waveheader); if (headerlen > 8) { gst_riff_strf_auds *header = NULL; GstBuffer *headerbuf; GstBuffer *extra; waveheader += 8; headerlen -= 8; headerbuf = gst_buffer_new_and_alloc (headerlen); gst_buffer_fill (headerbuf, 0, waveheader, headerlen); if (gst_riff_parse_strf_auds (GST_ELEMENT_CAST (qtdemux), headerbuf, &header, &extra)) { gst_caps_unref (stream->caps); \/* FIXME: Need to do something with the channel reorder map *\/ stream->caps = gst_riff_create_audio_caps (header->format, NULL, header, extra, NULL, NULL, NULL); if (extra) gst_buffer_unref (extra); g_free (header); } } } else GST_DEBUG (\"Didn't find waveheadernode for this codec\"); } g_node_destroy (wavenode); } } else if (esds) { gst_qtdemux_handle_esds (qtdemux, stream, esds, stream->pending_tags); } else { switch (fourcc) { #if 0 \/* FIXME: what is in the chunk? *\/ case FOURCC_QDMC: { gint len = QT_UINT32 (stsd_data); \/* seems to be always = 116 = 0x74 *\/ break; } #endif case FOURCC_QDM2: { gint len = QT_UINT32 (stsd_data); if (len > 0x4C) { GstBuffer *buf = gst_buffer_new_and_alloc (len - 0x4C); gst_buffer_fill (buf, 0, stsd_data + 0x4C, len - 0x4C); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); } gst_caps_set_simple (stream->caps, \"samplesize\", G_TYPE_INT, samplesize, NULL); break; } case FOURCC_alac: { GNode *alac, *wave = NULL; \/* apparently, m4a has this atom appended directly in the stsd entry, * while mov has it in a wave atom *\/ alac = qtdemux_tree_get_child_by_type (stsd, FOURCC_alac); if (alac) { \/* alac now refers to stsd entry atom *\/ wave = qtdemux_tree_get_child_by_type (alac, FOURCC_wave); if (wave) alac = qtdemux_tree_get_child_by_type (wave, FOURCC_alac); else alac = qtdemux_tree_get_child_by_type (alac, FOURCC_alac); } if (alac) { const guint8 *alac_data = alac->data; gint len = QT_UINT32 (alac->data); GstBuffer *buf; if (len < 36) { GST_DEBUG_OBJECT (qtdemux, \"discarding alac atom with unexpected len %d\", len); } else { \/* codec-data contains alac atom size and prefix, * ffmpeg likes it that way, not quite gst-ish though ...*\/ buf = gst_buffer_new_and_alloc (len); gst_buffer_fill (buf, 0, alac->data, len); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); stream->bytes_per_frame = QT_UINT32 (alac_data + 12); stream->n_channels = QT_UINT8 (alac_data + 21); stream->rate = QT_UINT32 (alac_data + 32); } } gst_caps_set_simple (stream->caps, \"samplesize\", G_TYPE_INT, samplesize, NULL); break; } case FOURCC_fLaC: { \/* The codingname of the sample entry is 'fLaC' *\/ GNode *flac = qtdemux_tree_get_child_by_type (stsd, FOURCC_fLaC); if (flac) { \/* The 'dfLa' box is added to the sample entry to convey initializing information for the decoder. *\/ const GNode *dfla = qtdemux_tree_get_child_by_type (flac, FOURCC_dfLa); if (dfla) { const guint32 len = QT_UINT32 (dfla->data); \/* Must contain at least dfLa box header (12), * METADATA_BLOCK_HEADER (4), METADATA_BLOCK_STREAMINFO (34) *\/ if (len < 50) { GST_DEBUG_OBJECT (qtdemux, \"discarding dfla atom with unexpected len %d\", len); } else { \/* skip dfLa header to get the METADATA_BLOCKs *\/ const guint8 *metadata_blocks = (guint8 *) dfla->data + 12; const guint32 metadata_blocks_len = len - 12; gchar *stream_marker = g_strdup (\"fLaC\"); GstBuffer *block = gst_buffer_new_wrapped (stream_marker, strlen (stream_marker)); guint32 index = 0; guint32 remainder = 0; guint32 block_size = 0; gboolean is_last = FALSE; GValue array = G_VALUE_INIT; GValue value = G_VALUE_INIT; g_value_init (&array, GST_TYPE_ARRAY); g_value_init (&value, GST_TYPE_BUFFER); gst_value_set_buffer (&value, block); gst_value_array_append_value (&array, &value); g_value_reset (&value); gst_buffer_unref (block); \/* check there's at least one METADATA_BLOCK_HEADER's worth * of data, and we haven't already finished parsing *\/ while (!is_last && ((index + 3) < metadata_blocks_len)) { remainder = metadata_blocks_len - index; \/* add the METADATA_BLOCK_HEADER size to the signalled size *\/ block_size = 4 + (metadata_blocks[index + 1] << 16) + (metadata_blocks[index + 2] << 8) + metadata_blocks[index + 3]; \/* be careful not to read off end of box *\/ if (block_size > remainder) { break; } is_last = metadata_blocks[index] >> 7; block = gst_buffer_new_and_alloc (block_size); gst_buffer_fill (block, 0, &metadata_blocks[index], block_size); gst_value_set_buffer (&value, block); gst_value_array_append_value (&array, &value); g_value_reset (&value); gst_buffer_unref (block); index += block_size; } \/* only append the metadata if we successfully read all of it *\/ if (is_last) { gst_structure_set_value (gst_caps_get_structure (stream->caps, 0), \"streamheader\", &array); } else { GST_WARNING_OBJECT (qtdemux, \"discarding all METADATA_BLOCKs due to invalid \" \"block_size %d at idx %d, rem %d\", block_size, index, remainder); } g_value_unset (&value); g_value_unset (&array); \/* The sample rate obtained from the stsd may not be accurate * since it cannot represent rates greater than 65535Hz, so * override that value with the sample rate from the * METADATA_BLOCK_STREAMINFO block *\/ stream->rate = (QT_UINT32 (metadata_blocks + 14) >> 12) & 0xFFFFF; } } } break; } case FOURCC_sawb: \/* Fallthrough! *\/ amrwb = TRUE; case FOURCC_samr: { gint len = QT_UINT32 (stsd_data); if (len > 0x34) { GstBuffer *buf = gst_buffer_new_and_alloc (len - 0x34); guint bitrate; gst_buffer_fill (buf, 0, stsd_data + 0x34, len - 0x34); \/* If we have enough data, let's try to get the 'damr' atom. See * the 3GPP container spec (26.244) for more details. *\/ if ((len - 0x34) > 8 && (bitrate = qtdemux_parse_amr_bitrate (buf, amrwb))) { gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_MAXIMUM_BITRATE, bitrate, NULL); } gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); } break; } case FOURCC_mp4a: { \/* mp4a atom withtout ESDS; Attempt to build codec data from atom *\/ gint len = QT_UINT32 (stsd_data); if (len >= 50) { guint16 sound_version = QT_UINT16 (stsd_data + 32); if (sound_version == 1) { guint16 channels = QT_UINT16 (stsd_data + 40); guint32 time_scale = QT_UINT32 (stsd_data + 46); guint8 codec_data[2]; GstBuffer *buf; gint profile = 2; \/* FIXME: Can this be determined somehow? There doesn't seem to be anything in mp4a atom that specifis compression *\/ gint sample_rate_index = gst_codec_utils_aac_get_index_from_sample_rate (time_scale); \/* build AAC codec data *\/ codec_data[0] = profile << 3; codec_data[0] |= ((sample_rate_index >> 1) & 0x7); codec_data[1] = (sample_rate_index & 0x01) << 7; codec_data[1] |= (channels & 0xF) << 3; buf = gst_buffer_new_and_alloc (2); gst_buffer_fill (buf, 0, codec_data, 2); gst_caps_set_simple (stream->caps, \"codec_data\", GST_TYPE_BUFFER, buf, NULL); gst_buffer_unref (buf); } } break; } default: GST_INFO_OBJECT (qtdemux, \"unhandled type %\" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc)); break; } } GST_INFO_OBJECT (qtdemux, \"type %\" GST_FOURCC_FORMAT \" caps %\" GST_PTR_FORMAT, GST_FOURCC_ARGS (fourcc), stream->caps); } else if (stream->subtype == FOURCC_strm) { if (fourcc == FOURCC_rtsp) { stream->redirect_uri = qtdemux_get_rtsp_uri_from_hndl (qtdemux, minf); } else { GST_INFO_OBJECT (qtdemux, \"unhandled stream type %\" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc)); goto unknown_stream; } stream->sampled = TRUE; } else if (stream->subtype == FOURCC_subp || stream->subtype == FOURCC_text || stream->subtype == FOURCC_sbtl || stream->subtype == FOURCC_subt) { stream->sampled = TRUE; stream->sparse = TRUE; stream->caps = qtdemux_sub_caps (qtdemux, stream, fourcc, stsd_data, &codec); if (codec) { gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_SUBTITLE_CODEC, codec, NULL); g_free (codec); codec = NULL; } \/* hunt for sort-of codec data *\/ switch (fourcc) { case FOURCC_mp4s: { GNode *mp4s = NULL; GNode *esds = NULL; \/* look for palette in a stsd->mp4s->esds sub-atom *\/ mp4s = qtdemux_tree_get_child_by_type (stsd, FOURCC_mp4s); if (mp4s) esds = qtdemux_tree_get_child_by_type (mp4s, FOURCC_esds); if (esds == NULL) { \/* Invalid STSD *\/ GST_LOG_OBJECT (qtdemux, \"Skipping invalid stsd: no esds child\"); break; } gst_qtdemux_handle_esds (qtdemux, stream, esds, stream->pending_tags); break; } default: GST_INFO_OBJECT (qtdemux, \"unhandled type %\" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc)); break; } GST_INFO_OBJECT (qtdemux, \"type %\" GST_FOURCC_FORMAT \" caps %\" GST_PTR_FORMAT, GST_FOURCC_ARGS (fourcc), stream->caps); } else { \/* everything in 1 sample *\/ stream->sampled = TRUE; stream->caps = qtdemux_generic_caps (qtdemux, stream, fourcc, stsd_data, &codec); if (stream->caps == NULL) goto unknown_stream; if (codec) { gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_SUBTITLE_CODEC, codec, NULL); g_free (codec); codec = NULL; } } \/* promote to sampled format *\/ if (stream->fourcc == FOURCC_samr) { \/* force mono 8000 Hz for AMR *\/ stream->sampled = TRUE; stream->n_channels = 1; stream->rate = 8000; } else if (stream->fourcc == FOURCC_sawb) { \/* force mono 16000 Hz for AMR-WB *\/ stream->sampled = TRUE; stream->n_channels = 1; stream->rate = 16000; } else if (stream->fourcc == FOURCC_mp4a) { stream->sampled = TRUE; } \/* collect sample information *\/ if (!qtdemux_stbl_init (qtdemux, stream, stbl)) goto samples_failed; if (qtdemux->fragmented) { guint64 offset; \/* need all moov samples as basis; probably not many if any at all *\/ \/* prevent moof parsing taking of at this time *\/ offset = qtdemux->moof_offset; qtdemux->moof_offset = 0; if (stream->n_samples && !qtdemux_parse_samples (qtdemux, stream, stream->n_samples - 1)) { qtdemux->moof_offset = offset; goto samples_failed; } qtdemux->moof_offset = 0; \/* movie duration more reliable in this case (e.g. mehd) *\/ if (qtdemux->segment.duration && GST_CLOCK_TIME_IS_VALID (qtdemux->segment.duration)) stream->duration = GSTTIME_TO_QTSTREAMTIME (stream, qtdemux->segment.duration); } \/* configure segments *\/ if (!qtdemux_parse_segments (qtdemux, stream, trak)) goto segments_failed; \/* add some language tag, if useful *\/ if (stream->lang_id[0] != '\\0' && strcmp (stream->lang_id, \"unk\") && strcmp (stream->lang_id, \"und\")) { const gchar *lang_code; \/* convert ISO 639-2 code to ISO 639-1 *\/ lang_code = gst_tag_get_language_code (stream->lang_id); gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_LANGUAGE_CODE, (lang_code) ? lang_code : stream->lang_id, NULL); } \/* Check for UDTA tags *\/ if ((udta = qtdemux_tree_get_child_by_type (trak, FOURCC_udta))) { qtdemux_parse_udta (qtdemux, stream->pending_tags, udta); } \/* now we are ready to add the stream *\/ if (qtdemux->n_streams >= GST_QTDEMUX_MAX_STREAMS) goto too_many_streams; if (!qtdemux->got_moov) { qtdemux->streams[qtdemux->n_streams] = stream; qtdemux->n_streams++; GST_DEBUG_OBJECT (qtdemux, \"n_streams is now %d\", qtdemux->n_streams); } return TRUE; \/* ERRORS *\/ skip_track: { GST_INFO_OBJECT (qtdemux, \"skip disabled track\"); if (new_stream) gst_qtdemux_stream_free (qtdemux, stream); return TRUE; } corrupt_file: { GST_ELEMENT_ERROR (qtdemux, STREAM, DEMUX, (_(\"This file is corrupt and cannot be played.\")), (NULL)); if (new_stream) gst_qtdemux_stream_free (qtdemux, stream); return FALSE; } error_encrypted: { GST_ELEMENT_ERROR (qtdemux, STREAM, DECRYPT, (NULL), (NULL)); if (new_stream) gst_qtdemux_stream_free (qtdemux, stream); return FALSE; } samples_failed: segments_failed: { \/* we posted an error already *\/ \/* free stbl sub-atoms *\/ gst_qtdemux_stbl_free (stream); if (new_stream) gst_qtdemux_stream_free (qtdemux, stream); return FALSE; } existing_stream: { GST_INFO_OBJECT (qtdemux, \"stream with track id %i already exists\", track_id); if (new_stream) gst_qtdemux_stream_free (qtdemux, stream); return TRUE; } unknown_stream: { GST_INFO_OBJECT (qtdemux, \"unknown subtype %\" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (stream->subtype)); if (new_stream) gst_qtdemux_stream_free (qtdemux, stream); return TRUE; } too_many_streams: { GST_ELEMENT_WARNING (qtdemux, STREAM, DEMUX, (_(\"This file contains too many streams. Only playing first %d\"), GST_QTDEMUX_MAX_STREAMS), (NULL)); return TRUE; } }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":377933,"input":"static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define CFormat \"\/Filter [ \/%s ]\\n\" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \\ { \\ if (xref != (MagickOffsetType *) NULL) \\ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \\ ThrowWriterException((exception),(message)); \\ } DisableMSCWarning(4310) static const char XMPProfile[]= { \"\\n\" \"\\n\" \" \\n\" \" \\n\" \" %s<\/xap:ModifyDate>\\n\" \" %s<\/xap:CreateDate>\\n\" \" %s<\/xap:MetadataDate>\\n\" \" %s<\/xap:CreatorTool>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" application\/pdf<\/dc:format>\\n\" \" \\n\" \" \\n\" \" %s<\/rdf:li>\\n\" \" <\/rdf:Alt>\\n\" \" <\/dc:title>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf<\/xapMM:DocumentID>\\n\" \" uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb<\/xapMM:InstanceID>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" %s<\/pdf:Producer>\\n\" \" <\/rdf:Description>\\n\" \" \\n\" \" 3<\/pdfaid:part>\\n\" \" B<\/pdfaid:conformance>\\n\" \" <\/rdf:Description>\\n\" \" <\/rdf:RDF>\\n\" \"<\/x:xmpmeta>\\n\" \"\\n\" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MagickPathExtent], buffer[MagickPathExtent], *escape, date[MagickPathExtent], **labels, page_geometry[MagickPathExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm utc_time; time_t seconds; unsigned char *pixels; \/* Open output image file. *\/ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); \/* Allocate X ref memory. *\/ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(xref,0,2048UL*sizeof(*xref)); \/* Write Info object. *\/ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->alpha_trait != UndefinedPixelTrait) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,\"icc\"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\\n'); } \/* Write Catalog object. *\/ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Pages %.20g 0 R\\n\", (double) object+1); else { (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Metadata %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Pages %.20g 0 R\\n\", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Type \/Catalog\"); option=GetImageOption(image_info,\"pdf:page-direction\"); if ((option != (const char *) NULL) && (LocaleCompare(option,\"right-to-left\") == 0)) (void) WriteBlobString(image,\"\/ViewerPreferences<<\/PageDirection\/R2L>>\\n\"); (void) WriteBlobString(image,\"\\n\"); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { char create_date[MagickPathExtent], modify_date[MagickPathExtent], timestamp[MagickPathExtent], xmp_profile[MagickPathExtent]; \/* Write XMP object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Subtype \/XML\\n\"); *modify_date='\\0'; value=GetImageProperty(image,\"date:modify\",exception); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MagickPathExtent); *create_date='\\0'; value=GetImageProperty(image,\"date:create\",exception); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MagickPathExtent); (void) FormatMagickTime(GetMagickTime(),MagickPathExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g\\n\", (double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Type \/Metadata\\n\"); (void) WriteBlobString(image,\">>\\nstream\\n\"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); } \/* Write Pages object. *\/ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/Pages\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Kids [ %.20g 0 R \", (double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; \/* Predict page object id's. *\/ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,\"icc\"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } (void) WriteBlobString(image,\"]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Count %.20g\\n\",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,\"icc\"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,exception) == MagickFalse) || (image->alpha_trait != UndefinedPixelTrait)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; \/* LZW compression is forbidden *\/ break; } case NoCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; \/* ASCII 85 compression is forbidden *\/ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Scale relative to dots-per-inch. *\/ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)\/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)\/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,\"PDF\") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry, MagickPathExtent); (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)\/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)\/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; \/* Write Page object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/Page\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Parent %.20g 0 R\\n\", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/Resources <<\\n\"); labels=(char **) NULL; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent, \"\/Font << \/F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent, \"\/XObject << \/Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ProcSet %.20g 0 R >>\\n\", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width\/resolution.x, 72.0*media_info.height\/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/CropBox [0 0 %g %g]\\n\",72.0*media_info.width\/resolution.x, 72.0*media_info.height\/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Contents %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Thumb %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Contents object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); (void) WriteBlobString(image,\"q\\n\"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,\"BT\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/F%.20g %g Tf\\n\", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\", labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"ET\\n\"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MagickPathExtent, \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x, (double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Im%.20g Do\\n\",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"Q\\n\"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Procset object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageC\",MagickPathExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageB\",MagickPathExtent); else (void) CopyMagickString(buffer,\"[ \/PDF \/Text \/ImageI\",MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\" ]\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Font object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (labels != (char **) NULL) { (void) WriteBlobString(image,\"\/Type \/Font\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Type1\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/F%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/BaseFont \/Helvetica\\n\"); (void) WriteBlobString(image,\"\/Encoding \/MacRomanEncoding\\n\"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write XObject object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"\/Type \/XObject\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/Im%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"\/Filter [ \/CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/DecodeParms [ << \" \"\/K %s \/BlackIs1 false \/Columns %.20g \/Rows %.20g >> ]\\n\",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ColorSpace %.20g 0 R\\n\", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->alpha_trait != UndefinedPixelTrait) { (void) FormatLocaleString(buffer,MagickPathExtent,\"\/SMask %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runoffset encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed DirectColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { \/* Dump number of colors and colormap. *\/ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) ((ssize_t) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) ((ssize_t) GetPixelIndex(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Colorspace object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); device=\"DeviceRGB\"; channels=0; if (image->colorspace == CMYKColorspace) { device=\"DeviceCMYK\"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { device=\"DeviceGray\"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device=\"DeviceRGB\"; channels=3; } profile=GetImageProfile(image,\"icc\"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"\/%s\\n\",device); else (void) FormatLocaleString(buffer,MagickPathExtent, \"[ \/Indexed \/%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; \/* Write ICC profile. *\/ (void) FormatLocaleString(buffer,MagickPathExtent, \"[\/ICCBased %.20g 0 R]\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n\/N %.20g\\n\" \"\/Filter \/ASCII85Decode\\n\/Length %.20g 0 R\\n\/Alternate \/%s\\n>>\\n\" \"stream\\n\",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"endstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Thumb object. *\/ SetGeometry(image,&geometry); (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception); if (tile_image == (Image *) NULL) return(MagickFalse); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"\/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"\/Filter [ \/CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/DecodeParms [ << \" \"\/K %s \/BlackIs1 false \/Columns %.20g \/Rows %.20g >> ]\\n\",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ColorSpace %.20g 0 R\\n\", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image, exception); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( tile_image,p))); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed DirectColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(tile_image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(tile_image,p))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } else { \/* Dump number of colors and colormap. *\/ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, \"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=(unsigned char) ((ssize_t) GetPixelIndex(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,(unsigned char) ((ssize_t) GetPixelIndex(tile_image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,\">>\\n\"); else { \/* Write Colormap object. *\/ if (compression == NoCompression) (void) WriteBlobString(image,\"\/Filter [ \/ASCII85Decode ]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); continue; } (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write softmask object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (image->alpha_trait == UndefinedPixelTrait) (void) WriteBlobString(image,\">>\\n\"); else { (void) WriteBlobString(image,\"\/Type \/XObject\\n\"); (void) WriteBlobString(image,\"\/Subtype \/Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Name \/Ma%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Width %.20g\\n\", (double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Height %.20g\\n\", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"\/ColorSpace \/DeviceGray\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent, \"\/BitsPerComponent %d\\n\",(compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; \/* Allocate pixel array. *\/ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); \/* Dump Runlength encoded pixels. *\/ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { \/* Dump uncompressed PseudoColor packets. *\/ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Length object. *\/ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); \/* Write Metadata object. *\/ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { escape=EscapeParenthesis(basename); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Title (%s)\\n\", escape); escape=DestroyString(escape); } else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { unsigned char hex_digits[16]; hex_digits[0]='0'; hex_digits[1]='1'; hex_digits[2]='2'; hex_digits[3]='3'; hex_digits[4]='4'; hex_digits[5]='5'; hex_digits[6]='6'; hex_digits[7]='7'; hex_digits[8]='8'; hex_digits[9]='9'; hex_digits[10]='A'; hex_digits[11]='B'; hex_digits[12]='C'; hex_digits[13]='D'; hex_digits[14]='E'; hex_digits[15]='F'; (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Title > 4) & 0x0f]); (void) WriteBlobByte(image,hex_digits[utf16[i] & 0x0f]); } (void) FormatLocaleString(buffer,MagickPathExtent,\">\\n\"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=GetMagickTime(); GetMagickUTCtime(&seconds,&utc_time); (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\", utc_time.tm_year+1900,utc_time.tm_mon+1,utc_time.tm_mday, utc_time.tm_hour,utc_time.tm_min,utc_time.tm_sec); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/CreationDate (%s)\\n\", date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ModDate (%s)\\n\",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Producer (%s)\\n\",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); \/* Write Xref object. *\/ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,\"xref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"0000000000 65535 f \\n\"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"trailer\\n\"); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Size %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Info %.20g 0 R\\n\",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/Root %.20g 0 R\\n\",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image,exception); (void) FormatLocaleString(buffer,MagickPathExtent,\"\/ID [<%s> <%s>]\\n\", GetImageProperty(image,\"signature\",exception), GetImageProperty(image,\"signature\",exception)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"startxref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"%%EOF\\n\"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":363532,"input":"smtp_setup_msg(void) { int done = 0; BOOL toomany = FALSE; BOOL discarded = FALSE; BOOL last_was_rej_mail = FALSE; BOOL last_was_rcpt = FALSE; void *reset_point = store_get(0); DEBUG(D_receive) debug_printf(\"smtp_setup_msg entered\\n\"); \/* Reset for start of new message. We allow one RSET not to be counted as a nonmail command, for those MTAs that insist on sending it between every message. Ditto for EHLO\/HELO and for STARTTLS, to allow for going in and out of TLS between messages (an Exim client may do this if it has messages queued up for the host). Note: we do NOT reset AUTH at this point. *\/ smtp_reset(reset_point); message_ended = END_NOTSTARTED; chunking_state = f.chunking_offered ? CHUNKING_OFFERED : CHUNKING_NOT_OFFERED; cmd_list[CMD_LIST_RSET].is_mail_cmd = TRUE; cmd_list[CMD_LIST_HELO].is_mail_cmd = TRUE; cmd_list[CMD_LIST_EHLO].is_mail_cmd = TRUE; #ifdef SUPPORT_TLS cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = TRUE; #endif \/* Set the local signal handler for SIGTERM - it tries to end off tidily *\/ had_command_sigterm = 0; os_non_restarting_signal(SIGTERM, command_sigterm_handler); \/* Batched SMTP is handled in a different function. *\/ if (smtp_batched_input) return smtp_setup_batch_msg(); \/* Deal with SMTP commands. This loop is exited by setting done to a POSITIVE value. The values are 2 larger than the required yield of the function. *\/ while (done <= 0) { const uschar **argv; uschar *etrn_command; uschar *etrn_serialize_key; uschar *errmess; uschar *log_msg, *smtp_code; uschar *user_msg = NULL; uschar *recipient = NULL; uschar *hello = NULL; uschar *s, *ss; BOOL was_rej_mail = FALSE; BOOL was_rcpt = FALSE; void (*oldsignal)(int); pid_t pid; int start, end, sender_domain, recipient_domain; int rc; int c; auth_instance *au; uschar *orcpt = NULL; int dsn_flags; gstring * g; #ifdef AUTH_TLS \/* Check once per STARTTLS or SSL-on-connect for a TLS AUTH *\/ if ( tls_in.active.sock >= 0 && tls_in.peercert && tls_in.certificate_verified && cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd ) { cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd = FALSE; for (au = auths; au; au = au->next) if (strcmpic(US\"tls\", au->driver_name) == 0) { if ( acl_smtp_auth && (rc = acl_check(ACL_WHERE_AUTH, NULL, acl_smtp_auth, &user_msg, &log_msg)) != OK ) done = smtp_handle_acl_fail(ACL_WHERE_AUTH, rc, user_msg, log_msg); else { smtp_cmd_data = NULL; if (smtp_in_auth(au, &s, &ss) == OK) { DEBUG(D_auth) debug_printf(\"tls auth succeeded\\n\"); } else { DEBUG(D_auth) debug_printf(\"tls auth not succeeded\\n\"); } } break; } } #endif #ifdef TCP_QUICKACK if (smtp_in) \/* Avoid pure-ACKs while in cmd pingpong phase *\/ (void) setsockopt(fileno(smtp_in), IPPROTO_TCP, TCP_QUICKACK, US &off, sizeof(off)); #endif switch(smtp_read_command( #ifdef EXPERIMENTAL_PIPE_CONNECT !fl.pipe_connect_acceptable, #else TRUE, #endif GETC_BUFFER_UNLIMITED)) { \/* The AUTH command is not permitted to occur inside a transaction, and may occur successfully only once per connection. Actually, that isn't quite true. When TLS is started, all previous information about a connection must be discarded, so a new AUTH is permitted at that time. AUTH may only be used when it has been advertised. However, it seems that there are clients that send AUTH when it hasn't been advertised, some of them even doing this after HELO. And there are MTAs that accept this. Sigh. So there's a get-out that allows this to happen. AUTH is initially labelled as a \"nonmail command\" so that one occurrence doesn't get counted. We change the label here so that multiple failing AUTHS will eventually hit the nonmail threshold. *\/ case AUTH_CMD: HAD(SCH_AUTH); authentication_failed = TRUE; cmd_list[CMD_LIST_AUTH].is_mail_cmd = FALSE; if (!fl.auth_advertised && !f.allow_auth_unadvertised) { done = synprot_error(L_smtp_protocol_error, 503, NULL, US\"AUTH command used when not advertised\"); break; } if (sender_host_authenticated) { done = synprot_error(L_smtp_protocol_error, 503, NULL, US\"already authenticated\"); break; } if (sender_address) { done = synprot_error(L_smtp_protocol_error, 503, NULL, US\"not permitted in mail transaction\"); break; } \/* Check the ACL *\/ if ( acl_smtp_auth && (rc = acl_check(ACL_WHERE_AUTH, NULL, acl_smtp_auth, &user_msg, &log_msg)) != OK ) { done = smtp_handle_acl_fail(ACL_WHERE_AUTH, rc, user_msg, log_msg); break; } \/* Find the name of the requested authentication mechanism. *\/ s = smtp_cmd_data; while ((c = *smtp_cmd_data) != 0 && !isspace(c)) { if (!isalnum(c) && c != '-' && c != '_') { done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"invalid character in authentication mechanism name\"); goto COMMAND_LOOP; } smtp_cmd_data++; } \/* If not at the end of the line, we must be at white space. Terminate the name and move the pointer on to any data that may be present. *\/ if (*smtp_cmd_data != 0) { *smtp_cmd_data++ = 0; while (isspace(*smtp_cmd_data)) smtp_cmd_data++; } \/* Search for an authentication mechanism which is configured for use as a server and which has been advertised (unless, sigh, allow_auth_ unadvertised is set). *\/ for (au = auths; au; au = au->next) if (strcmpic(s, au->public_name) == 0 && au->server && (au->advertised || f.allow_auth_unadvertised)) break; if (au) { c = smtp_in_auth(au, &s, &ss); smtp_printf(\"%s\\r\\n\", FALSE, s); if (c != OK) log_write(0, LOG_MAIN|LOG_REJECT, \"%s authenticator failed for %s: %s\", au->name, host_and_ident(FALSE), ss); } else done = synprot_error(L_smtp_protocol_error, 504, NULL, string_sprintf(\"%s authentication mechanism not supported\", s)); break; \/* AUTH_CMD *\/ \/* The HELO\/EHLO commands are permitted to appear in the middle of a session as well as at the beginning. They have the effect of a reset in addition to their other functions. Their absence at the start cannot be taken to be an error. RFC 2821 says: If the EHLO command is not acceptable to the SMTP server, 501, 500, or 502 failure replies MUST be returned as appropriate. The SMTP server MUST stay in the same state after transmitting these replies that it was in before the EHLO was received. Therefore, we do not do the reset until after checking the command for acceptability. This change was made for Exim release 4.11. Previously it did the reset first. *\/ case HELO_CMD: HAD(SCH_HELO); hello = US\"HELO\"; fl.esmtp = FALSE; goto HELO_EHLO; case EHLO_CMD: HAD(SCH_EHLO); hello = US\"EHLO\"; fl.esmtp = TRUE; HELO_EHLO: \/* Common code for HELO and EHLO *\/ cmd_list[CMD_LIST_HELO].is_mail_cmd = FALSE; cmd_list[CMD_LIST_EHLO].is_mail_cmd = FALSE; \/* Reject the HELO if its argument was invalid or non-existent. A successful check causes the argument to be saved in malloc store. *\/ if (!check_helo(smtp_cmd_data)) { smtp_printf(\"501 Syntactically invalid %s argument(s)\\r\\n\", FALSE, hello); log_write(0, LOG_MAIN|LOG_REJECT, \"rejected %s from %s: syntactically \" \"invalid argument(s): %s\", hello, host_and_ident(FALSE), *smtp_cmd_argument == 0 ? US\"(no argument given)\" : string_printing(smtp_cmd_argument)); if (++synprot_error_count > smtp_max_synprot_errors) { log_write(0, LOG_MAIN|LOG_REJECT, \"SMTP call from %s dropped: too many \" \"syntax or protocol errors (last command was \\\"%s\\\")\", host_and_ident(FALSE), string_printing(smtp_cmd_buffer)); done = 1; } break; } \/* If sender_host_unknown is true, we have got here via the -bs interface, not called from inetd. Otherwise, we are running an IP connection and the host address will be set. If the helo name is the primary name of this host and we haven't done a reverse lookup, force one now. If helo_required is set, ensure that the HELO name matches the actual host. If helo_verify is set, do the same check, but softly. *\/ if (!f.sender_host_unknown) { BOOL old_helo_verified = f.helo_verified; uschar *p = smtp_cmd_data; while (*p != 0 && !isspace(*p)) { *p = tolower(*p); p++; } *p = 0; \/* Force a reverse lookup if HELO quoted something in helo_lookup_domains because otherwise the log can be confusing. *\/ if ( !sender_host_name && (deliver_domain = sender_helo_name, \/* set $domain *\/ match_isinlist(sender_helo_name, CUSS &helo_lookup_domains, 0, &domainlist_anchor, NULL, MCL_DOMAIN, TRUE, NULL)) == OK) (void)host_name_lookup(); \/* Rebuild the fullhost info to include the HELO name (and the real name if it was looked up.) *\/ host_build_sender_fullhost(); \/* Rebuild *\/ set_process_info(\"handling%s incoming connection from %s\", tls_in.active.sock >= 0 ? \" TLS\" : \"\", host_and_ident(FALSE)); \/* Verify if configured. This doesn't give much security, but it does make some people happy to be able to do it. If helo_required is set, (host matches helo_verify_hosts) failure forces rejection. If helo_verify is set (host matches helo_try_verify_hosts), it does not. This is perhaps now obsolescent, since the verification can now be requested selectively at ACL time. *\/ f.helo_verified = f.helo_verify_failed = sender_helo_dnssec = FALSE; if (fl.helo_required || fl.helo_verify) { BOOL tempfail = !smtp_verify_helo(); if (!f.helo_verified) { if (fl.helo_required) { smtp_printf(\"%d %s argument does not match calling host\\r\\n\", FALSE, tempfail? 451 : 550, hello); log_write(0, LOG_MAIN|LOG_REJECT, \"%srejected \\\"%s %s\\\" from %s\", tempfail? \"temporarily \" : \"\", hello, sender_helo_name, host_and_ident(FALSE)); f.helo_verified = old_helo_verified; break; \/* End of HELO\/EHLO processing *\/ } HDEBUG(D_all) debug_printf(\"%s verification failed but host is in \" \"helo_try_verify_hosts\\n\", hello); } } } #ifdef SUPPORT_SPF \/* set up SPF context *\/ spf_init(sender_helo_name, sender_host_address); #endif \/* Apply an ACL check if one is defined; afterwards, recheck synchronization in case the client started sending in a delay. *\/ if (acl_smtp_helo) if ((rc = acl_check(ACL_WHERE_HELO, NULL, acl_smtp_helo, &user_msg, &log_msg)) != OK) { done = smtp_handle_acl_fail(ACL_WHERE_HELO, rc, user_msg, log_msg); if (sender_helo_name) { store_free(sender_helo_name); sender_helo_name = NULL; } host_build_sender_fullhost(); \/* Rebuild *\/ break; } #ifdef EXPERIMENTAL_PIPE_CONNECT else if (!fl.pipe_connect_acceptable && !check_sync()) #else else if (!check_sync()) #endif goto SYNC_FAILURE; \/* Generate an OK reply. The default string includes the ident if present, and also the IP address if present. Reflecting back the ident is intended as a deterrent to mail forgers. For maximum efficiency, and also because some broken systems expect each response to be in a single packet, arrange that the entire reply is sent in one write(). *\/ fl.auth_advertised = FALSE; f.smtp_in_pipelining_advertised = FALSE; #ifdef SUPPORT_TLS fl.tls_advertised = FALSE; # ifdef EXPERIMENTAL_REQUIRETLS fl.requiretls_advertised = FALSE; # endif #endif fl.dsn_advertised = FALSE; #ifdef SUPPORT_I18N fl.smtputf8_advertised = FALSE; #endif smtp_code = US\"250 \"; \/* Default response code plus space*\/ if (!user_msg) { s = string_sprintf(\"%.3s %s Hello %s%s%s\", smtp_code, smtp_active_hostname, sender_ident ? sender_ident : US\"\", sender_ident ? US\" at \" : US\"\", sender_host_name ? sender_host_name : sender_helo_name); g = string_cat(NULL, s); if (sender_host_address) { g = string_catn(g, US\" [\", 2); g = string_cat (g, sender_host_address); g = string_catn(g, US\"]\", 1); } } \/* A user-supplied EHLO greeting may not contain more than one line. Note that the code returned by smtp_message_code() includes the terminating whitespace character. *\/ else { char *ss; int codelen = 4; smtp_message_code(&smtp_code, &codelen, &user_msg, NULL, TRUE); s = string_sprintf(\"%.*s%s\", codelen, smtp_code, user_msg); if ((ss = strpbrk(CS s, \"\\r\\n\")) != NULL) { log_write(0, LOG_MAIN|LOG_PANIC, \"EHLO\/HELO response must not contain \" \"newlines: message truncated: %s\", string_printing(s)); *ss = 0; } g = string_cat(NULL, s); } g = string_catn(g, US\"\\r\\n\", 2); \/* If we received EHLO, we must create a multiline response which includes the functions supported. *\/ if (fl.esmtp) { g->s[3] = '-'; \/* I'm not entirely happy with this, as an MTA is supposed to check that it has enough room to accept a message of maximum size before it sends this. However, there seems little point in not sending it. The actual size check happens later at MAIL FROM time. By postponing it till then, VRFY and EXPN can be used after EHLO when space is short. *\/ if (thismessage_size_limit > 0) { sprintf(CS big_buffer, \"%.3s-SIZE %d\\r\\n\", smtp_code, thismessage_size_limit); g = string_cat(g, big_buffer); } else { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-SIZE\\r\\n\", 7); } \/* Exim does not do protocol conversion or data conversion. It is 8-bit clean; if it has an 8-bit character in its hand, it just sends it. It cannot therefore specify 8BITMIME and remain consistent with the RFCs. However, some users want this option simply in order to stop MUAs mangling messages that contain top-bit-set characters. It is therefore provided as an option. *\/ if (accept_8bitmime) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-8BITMIME\\r\\n\", 11); } \/* Advertise DSN support if configured to do so. *\/ if (verify_check_host(&dsn_advertise_hosts) != FAIL) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-DSN\\r\\n\", 6); fl.dsn_advertised = TRUE; } \/* Advertise ETRN\/VRFY\/EXPN if there's are ACL checking whether a host is permitted to issue them; a check is made when any host actually tries. *\/ if (acl_smtp_etrn) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-ETRN\\r\\n\", 7); } if (acl_smtp_vrfy) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-VRFY\\r\\n\", 7); } if (acl_smtp_expn) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-EXPN\\r\\n\", 7); } \/* Exim is quite happy with pipelining, so let the other end know that it is safe to use it, unless advertising is disabled. *\/ if ( f.pipelining_enable && verify_check_host(&pipelining_advertise_hosts) == OK) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-PIPELINING\\r\\n\", 13); sync_cmd_limit = NON_SYNC_CMD_PIPELINING; f.smtp_in_pipelining_advertised = TRUE; #ifdef EXPERIMENTAL_PIPE_CONNECT if (fl.pipe_connect_acceptable) { f.smtp_in_early_pipe_advertised = TRUE; g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-\" EARLY_PIPE_FEATURE_NAME \"\\r\\n\", EARLY_PIPE_FEATURE_LEN+3); } #endif } \/* If any server authentication mechanisms are configured, advertise them if the current host is in auth_advertise_hosts. The problem with advertising always is that some clients then require users to authenticate (and aren't configurable otherwise) even though it may not be necessary (e.g. if the host is in host_accept_relay). RFC 2222 states that SASL mechanism names contain only upper case letters, so output the names in upper case, though we actually recognize them in either case in the AUTH command. *\/ if ( auths #ifdef AUTH_TLS && !sender_host_authenticated #endif && verify_check_host(&auth_advertise_hosts) == OK ) { auth_instance *au; BOOL first = TRUE; for (au = auths; au; au = au->next) { au->advertised = FALSE; if (au->server) { DEBUG(D_auth+D_expand) debug_printf_indent( \"Evaluating advertise_condition for %s athenticator\\n\", au->public_name); if ( !au->advertise_condition || expand_check_condition(au->advertise_condition, au->name, US\"authenticator\") ) { int saveptr; if (first) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-AUTH\", 5); first = FALSE; fl.auth_advertised = TRUE; } saveptr = g->ptr; g = string_catn(g, US\" \", 1); g = string_cat (g, au->public_name); while (++saveptr < g->ptr) g->s[saveptr] = toupper(g->s[saveptr]); au->advertised = TRUE; } } } if (!first) g = string_catn(g, US\"\\r\\n\", 2); } \/* RFC 3030 CHUNKING *\/ if (verify_check_host(&chunking_advertise_hosts) != FAIL) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-CHUNKING\\r\\n\", 11); f.chunking_offered = TRUE; chunking_state = CHUNKING_OFFERED; } \/* Advertise TLS (Transport Level Security) aka SSL (Secure Socket Layer) if it has been included in the binary, and the host matches tls_advertise_hosts. We must *not* advertise if we are already in a secure connection. *\/ #ifdef SUPPORT_TLS if (tls_in.active.sock < 0 && verify_check_host(&tls_advertise_hosts) != FAIL) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-STARTTLS\\r\\n\", 11); fl.tls_advertised = TRUE; } # ifdef EXPERIMENTAL_REQUIRETLS \/* Advertise REQUIRETLS only once we are in a secure connection *\/ if ( tls_in.active.sock >= 0 && verify_check_host(&tls_advertise_requiretls) != FAIL) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-REQUIRETLS\\r\\n\", 13); fl.requiretls_advertised = TRUE; } # endif #endif #ifndef DISABLE_PRDR \/* Per Recipient Data Response, draft by Eric A. Hall extending RFC *\/ if (prdr_enable) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-PRDR\\r\\n\", 7); } #endif #ifdef SUPPORT_I18N if ( accept_8bitmime && verify_check_host(&smtputf8_advertise_hosts) != FAIL) { g = string_catn(g, smtp_code, 3); g = string_catn(g, US\"-SMTPUTF8\\r\\n\", 11); fl.smtputf8_advertised = TRUE; } #endif \/* Finish off the multiline reply with one that is always available. *\/ g = string_catn(g, smtp_code, 3); g = string_catn(g, US\" HELP\\r\\n\", 7); } \/* Terminate the string (for debug), write it, and note that HELO\/EHLO has been seen. *\/ #ifdef SUPPORT_TLS if (tls_in.active.sock >= 0) (void)tls_write(NULL, g->s, g->ptr, # ifdef EXPERIMENTAL_PIPE_CONNECT fl.pipe_connect_acceptable && pipeline_connect_sends()); # else FALSE); # endif else #endif { int i = fwrite(g->s, 1, g->ptr, smtp_out); i = i; \/* compiler quietening *\/ } DEBUG(D_receive) { uschar *cr; (void) string_from_gstring(g); while ((cr = Ustrchr(g->s, '\\r')) != NULL) \/* lose CRs *\/ memmove(cr, cr + 1, (g->ptr--) - (cr - g->s)); debug_printf(\"SMTP>> %s\", g->s); } fl.helo_seen = TRUE; \/* Reset the protocol and the state, abandoning any previous message. *\/ received_protocol = (sender_host_address ? protocols : protocols_local) [ (fl.esmtp ? pextend + (sender_host_authenticated ? pauthed : 0) : pnormal) + (tls_in.active.sock >= 0 ? pcrpted : 0) ]; cancel_cutthrough_connection(TRUE, US\"sent EHLO response\"); smtp_reset(reset_point); toomany = FALSE; break; \/* HELO\/EHLO *\/ \/* The MAIL command requires an address as an operand. All we do here is to parse it for syntactic correctness. The form \"<>\" is a special case which converts into an empty string. The start\/end pointers in the original are not used further for this address, as it is the canonical extracted address which is all that is kept. *\/ case MAIL_CMD: HAD(SCH_MAIL); smtp_mailcmd_count++; \/* Count for limit and ratelimit *\/ was_rej_mail = TRUE; \/* Reset if accepted *\/ env_mail_type_t * mail_args; \/* Sanity check & validate args *\/ if (fl.helo_required && !fl.helo_seen) { smtp_printf(\"503 HELO or EHLO required\\r\\n\", FALSE); log_write(0, LOG_MAIN|LOG_REJECT, \"rejected MAIL from %s: no \" \"HELO\/EHLO given\", host_and_ident(FALSE)); break; } if (sender_address) { done = synprot_error(L_smtp_protocol_error, 503, NULL, US\"sender already given\"); break; } if (!*smtp_cmd_data) { done = synprot_error(L_smtp_protocol_error, 501, NULL, US\"MAIL must have an address operand\"); break; } \/* Check to see if the limit for messages per connection would be exceeded by accepting further messages. *\/ if (smtp_accept_max_per_connection > 0 && smtp_mailcmd_count > smtp_accept_max_per_connection) { smtp_printf(\"421 too many messages in this connection\\r\\n\", FALSE); log_write(0, LOG_MAIN|LOG_REJECT, \"rejected MAIL command %s: too many \" \"messages in one connection\", host_and_ident(TRUE)); break; } \/* Reset for start of message - even if this is going to fail, we obviously need to throw away any previous data. *\/ cancel_cutthrough_connection(TRUE, US\"MAIL received\"); smtp_reset(reset_point); toomany = FALSE; sender_data = recipient_data = NULL; \/* Loop, checking for ESMTP additions to the MAIL FROM command. *\/ if (fl.esmtp) for(;;) { uschar *name, *value, *end; unsigned long int size; BOOL arg_error = FALSE; if (!extract_option(&name, &value)) break; for (mail_args = env_mail_type_list; mail_args->value != ENV_MAIL_OPT_NULL; mail_args++ ) if (strcmpic(name, mail_args->name) == 0) break; if (mail_args->need_value && strcmpic(value, US\"\") == 0) break; switch(mail_args->value) { \/* Handle SIZE= by reading the value. We don't do the check till later, in order to be able to log the sender address on failure. *\/ case ENV_MAIL_OPT_SIZE: if (((size = Ustrtoul(value, &end, 10)), *end == 0)) { if ((size == ULONG_MAX && errno == ERANGE) || size > INT_MAX) size = INT_MAX; message_size = (int)size; } else arg_error = TRUE; break; \/* If this session was initiated with EHLO and accept_8bitmime is set, Exim will have indicated that it supports the BODY=8BITMIME option. In fact, it does not support this according to the RFCs, in that it does not take any special action for forwarding messages containing 8-bit characters. That is why accept_8bitmime is not the default setting, but some sites want the action that is provided. We recognize both \"8BITMIME\" and \"7BIT\" as body types, but take no action. *\/ case ENV_MAIL_OPT_BODY: if (accept_8bitmime) { if (strcmpic(value, US\"8BITMIME\") == 0) body_8bitmime = 8; else if (strcmpic(value, US\"7BIT\") == 0) body_8bitmime = 7; else { body_8bitmime = 0; done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"invalid data for BODY\"); goto COMMAND_LOOP; } DEBUG(D_receive) debug_printf(\"8BITMIME: %d\\n\", body_8bitmime); break; } arg_error = TRUE; break; \/* Handle the two DSN options, but only if configured to do so (which will have caused \"DSN\" to be given in the EHLO response). The code itself is included only if configured in at build time. *\/ case ENV_MAIL_OPT_RET: if (fl.dsn_advertised) { \/* Check if RET has already been set *\/ if (dsn_ret > 0) { done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"RET can be specified once only\"); goto COMMAND_LOOP; } dsn_ret = strcmpic(value, US\"HDRS\") == 0 ? dsn_ret_hdrs : strcmpic(value, US\"FULL\") == 0 ? dsn_ret_full : 0; DEBUG(D_receive) debug_printf(\"DSN_RET: %d\\n\", dsn_ret); \/* Check for invalid invalid value, and exit with error *\/ if (dsn_ret == 0) { done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"Value for RET is invalid\"); goto COMMAND_LOOP; } } break; case ENV_MAIL_OPT_ENVID: if (fl.dsn_advertised) { \/* Check if the dsn envid has been already set *\/ if (dsn_envid) { done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"ENVID can be specified once only\"); goto COMMAND_LOOP; } dsn_envid = string_copy(value); DEBUG(D_receive) debug_printf(\"DSN_ENVID: %s\\n\", dsn_envid); } break; \/* Handle the AUTH extension. If the value given is not \"<>\" and either the ACL says \"yes\" or there is no ACL but the sending host is authenticated, we set it up as the authenticated sender. However, if the authenticator set a condition to be tested, we ignore AUTH on MAIL unless the condition is met. The value of AUTH is an xtext, which means that +, = and cntrl chars are coded in hex; however \"<>\" is unaffected by this coding. *\/ case ENV_MAIL_OPT_AUTH: if (Ustrcmp(value, \"<>\") != 0) { int rc; uschar *ignore_msg; if (auth_xtextdecode(value, &authenticated_sender) < 0) { \/* Put back terminator overrides for error message *\/ value[-1] = '='; name[-1] = ' '; done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"invalid data for AUTH\"); goto COMMAND_LOOP; } if (!acl_smtp_mailauth) { ignore_msg = US\"client not authenticated\"; rc = sender_host_authenticated ? OK : FAIL; } else { ignore_msg = US\"rejected by ACL\"; rc = acl_check(ACL_WHERE_MAILAUTH, NULL, acl_smtp_mailauth, &user_msg, &log_msg); } switch (rc) { case OK: if (authenticated_by == NULL || authenticated_by->mail_auth_condition == NULL || expand_check_condition(authenticated_by->mail_auth_condition, authenticated_by->name, US\"authenticator\")) break; \/* Accept the AUTH *\/ ignore_msg = US\"server_mail_auth_condition failed\"; if (authenticated_id != NULL) ignore_msg = string_sprintf(\"%s: authenticated ID=\\\"%s\\\"\", ignore_msg, authenticated_id); \/* Fall through *\/ case FAIL: authenticated_sender = NULL; log_write(0, LOG_MAIN, \"ignoring AUTH=%s from %s (%s)\", value, host_and_ident(TRUE), ignore_msg); break; \/* Should only get DEFER or ERROR here. Put back terminator overrides for error message *\/ default: value[-1] = '='; name[-1] = ' '; (void)smtp_handle_acl_fail(ACL_WHERE_MAILAUTH, rc, user_msg, log_msg); goto COMMAND_LOOP; } } break; #ifndef DISABLE_PRDR case ENV_MAIL_OPT_PRDR: if (prdr_enable) prdr_requested = TRUE; break; #endif #ifdef SUPPORT_I18N case ENV_MAIL_OPT_UTF8: if (!fl.smtputf8_advertised) { done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"SMTPUTF8 used when not advertised\"); goto COMMAND_LOOP; } DEBUG(D_receive) debug_printf(\"smtputf8 requested\\n\"); message_smtputf8 = allow_utf8_domains = TRUE; if (Ustrncmp(received_protocol, US\"utf8\", 4) != 0) { int old_pool = store_pool; store_pool = POOL_PERM; received_protocol = string_sprintf(\"utf8%s\", received_protocol); store_pool = old_pool; } break; #endif #if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_REQUIRETLS) case ENV_MAIL_OPT_REQTLS: { uschar * r, * t; if (!fl.requiretls_advertised) { done = synprot_error(L_smtp_syntax_error, 555, NULL, US\"unadvertised MAIL option: REQUIRETLS\"); goto COMMAND_LOOP; } DEBUG(D_receive) debug_printf(\"requiretls requested\\n\"); tls_requiretls = REQUIRETLS_MSG; r = string_copy_malloc(received_protocol); if ((t = Ustrrchr(r, 's'))) *t = 'S'; received_protocol = r; } break; #endif \/* No valid option. Stick back the terminator characters and break the loop. Do the name-terminator second as extract_option sets value==name when it found no equal-sign. An error for a malformed address will occur. *\/ case ENV_MAIL_OPT_NULL: value[-1] = '='; name[-1] = ' '; arg_error = TRUE; break; default: assert(0); } \/* Break out of for loop if switch() had bad argument or when start of the email address is reached *\/ if (arg_error) break; } #if defined(SUPPORT_TLS) && defined(EXPERIMENTAL_REQUIRETLS) if (tls_requiretls & REQUIRETLS_MSG) { \/* Ensure headers-only bounces whether a RET option was given or not. *\/ DEBUG(D_receive) if (dsn_ret == dsn_ret_full) debug_printf(\"requiretls override: dsn_ret_full -> dsn_ret_hdrs\\n\"); dsn_ret = dsn_ret_hdrs; } #endif \/* If we have passed the threshold for rate limiting, apply the current delay, and update it for next time, provided this is a limited host. *\/ if (smtp_mailcmd_count > smtp_rlm_threshold && verify_check_host(&smtp_ratelimit_hosts) == OK) { DEBUG(D_receive) debug_printf(\"rate limit MAIL: delay %.3g sec\\n\", smtp_delay_mail\/1000.0); millisleep((int)smtp_delay_mail); smtp_delay_mail *= smtp_rlm_factor; if (smtp_delay_mail > (double)smtp_rlm_limit) smtp_delay_mail = (double)smtp_rlm_limit; } \/* Now extract the address, first applying any SMTP-time rewriting. The TRUE flag allows \"<>\" as a sender address. *\/ raw_sender = rewrite_existflags & rewrite_smtp ? rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US\"\", global_rewrite_rules) : smtp_cmd_data; raw_sender = parse_extract_address(raw_sender, &errmess, &start, &end, &sender_domain, TRUE); if (!raw_sender) { done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess); break; } sender_address = raw_sender; \/* If there is a configured size limit for mail, check that this message doesn't exceed it. The check is postponed to this point so that the sender can be logged. *\/ if (thismessage_size_limit > 0 && message_size > thismessage_size_limit) { smtp_printf(\"552 Message size exceeds maximum permitted\\r\\n\", FALSE); log_write(L_size_reject, LOG_MAIN|LOG_REJECT, \"rejected MAIL FROM:<%s> %s: \" \"message too big: size%s=%d max=%d\", sender_address, host_and_ident(TRUE), (message_size == INT_MAX)? \">\" : \"\", message_size, thismessage_size_limit); sender_address = NULL; break; } \/* Check there is enough space on the disk unless configured not to. When smtp_check_spool_space is set, the check is for thismessage_size_limit plus the current message - i.e. we accept the message only if it won't reduce the space below the threshold. Add 5000 to the size to allow for overheads such as the Received: line and storing of recipients, etc. By putting the check here, even when SIZE is not given, it allow VRFY and EXPN etc. to be used when space is short. *\/ if (!receive_check_fs( (smtp_check_spool_space && message_size >= 0)? message_size + 5000 : 0)) { smtp_printf(\"452 Space shortage, please try later\\r\\n\", FALSE); sender_address = NULL; break; } \/* If sender_address is unqualified, reject it, unless this is a locally generated message, or the sending host or net is permitted to send unqualified addresses - typically local machines behaving as MUAs - in which case just qualify the address. The flag is set above at the start of the SMTP connection. *\/ if (!sender_domain && *sender_address) if (f.allow_unqualified_sender) { sender_domain = Ustrlen(sender_address) + 1; sender_address = rewrite_address_qualify(sender_address, FALSE); DEBUG(D_receive) debug_printf(\"unqualified address %s accepted\\n\", raw_sender); } else { smtp_printf(\"501 %s: sender address must contain a domain\\r\\n\", FALSE, smtp_cmd_data); log_write(L_smtp_syntax_error, LOG_MAIN|LOG_REJECT, \"unqualified sender rejected: <%s> %s%s\", raw_sender, host_and_ident(TRUE), host_lookup_msg); sender_address = NULL; break; } \/* Apply an ACL check if one is defined, before responding. Afterwards, when pipelining is not advertised, do another sync check in case the ACL delayed and the client started sending in the meantime. *\/ if (acl_smtp_mail) { rc = acl_check(ACL_WHERE_MAIL, NULL, acl_smtp_mail, &user_msg, &log_msg); if (rc == OK && !f.smtp_in_pipelining_advertised && !check_sync()) goto SYNC_FAILURE; } else rc = OK; if (rc == OK || rc == DISCARD) { BOOL more = pipeline_response(); if (!user_msg) smtp_printf(\"%s%s%s\", more, US\"250 OK\", #ifndef DISABLE_PRDR prdr_requested ? US\", PRDR Requested\" : US\"\", #else US\"\", #endif US\"\\r\\n\"); else { #ifndef DISABLE_PRDR if (prdr_requested) user_msg = string_sprintf(\"%s%s\", user_msg, US\", PRDR Requested\"); #endif smtp_user_msg(US\"250\", user_msg); } smtp_delay_rcpt = smtp_rlr_base; f.recipients_discarded = (rc == DISCARD); was_rej_mail = FALSE; } else { done = smtp_handle_acl_fail(ACL_WHERE_MAIL, rc, user_msg, log_msg); sender_address = NULL; } break; \/* The RCPT command requires an address as an operand. There may be any number of RCPT commands, specifying multiple recipients. We build them all into a data structure. The start\/end values given by parse_extract_address are not used, as we keep only the extracted address. *\/ case RCPT_CMD: HAD(SCH_RCPT); rcpt_count++; was_rcpt = fl.rcpt_in_progress = TRUE; \/* There must be a sender address; if the sender was rejected and pipelining was advertised, we assume the client was pipelining, and do not count this as a protocol error. Reset was_rej_mail so that further RCPTs get the same treatment. *\/ if (sender_address == NULL) { if (f.smtp_in_pipelining_advertised && last_was_rej_mail) { smtp_printf(\"503 sender not yet given\\r\\n\", FALSE); was_rej_mail = TRUE; } else { done = synprot_error(L_smtp_protocol_error, 503, NULL, US\"sender not yet given\"); was_rcpt = FALSE; \/* Not a valid RCPT *\/ } rcpt_fail_count++; break; } \/* Check for an operand *\/ if (smtp_cmd_data[0] == 0) { done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"RCPT must have an address operand\"); rcpt_fail_count++; break; } \/* Set the DSN flags orcpt and dsn_flags from the session*\/ orcpt = NULL; dsn_flags = 0; if (fl.esmtp) for(;;) { uschar *name, *value; if (!extract_option(&name, &value)) break; if (fl.dsn_advertised && strcmpic(name, US\"ORCPT\") == 0) { \/* Check whether orcpt has been already set *\/ if (orcpt) { done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"ORCPT can be specified once only\"); goto COMMAND_LOOP; } orcpt = string_copy(value); DEBUG(D_receive) debug_printf(\"DSN orcpt: %s\\n\", orcpt); } else if (fl.dsn_advertised && strcmpic(name, US\"NOTIFY\") == 0) { \/* Check if the notify flags have been already set *\/ if (dsn_flags > 0) { done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"NOTIFY can be specified once only\"); goto COMMAND_LOOP; } if (strcmpic(value, US\"NEVER\") == 0) dsn_flags |= rf_notify_never; else { uschar *p = value; while (*p != 0) { uschar *pp = p; while (*pp != 0 && *pp != ',') pp++; if (*pp == ',') *pp++ = 0; if (strcmpic(p, US\"SUCCESS\") == 0) { DEBUG(D_receive) debug_printf(\"DSN: Setting notify success\\n\"); dsn_flags |= rf_notify_success; } else if (strcmpic(p, US\"FAILURE\") == 0) { DEBUG(D_receive) debug_printf(\"DSN: Setting notify failure\\n\"); dsn_flags |= rf_notify_failure; } else if (strcmpic(p, US\"DELAY\") == 0) { DEBUG(D_receive) debug_printf(\"DSN: Setting notify delay\\n\"); dsn_flags |= rf_notify_delay; } else { \/* Catch any strange values *\/ done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"Invalid value for NOTIFY parameter\"); goto COMMAND_LOOP; } p = pp; } DEBUG(D_receive) debug_printf(\"DSN Flags: %x\\n\", dsn_flags); } } \/* Unknown option. Stick back the terminator characters and break the loop. An error for a malformed address will occur. *\/ else { DEBUG(D_receive) debug_printf(\"Invalid RCPT option: %s : %s\\n\", name, value); name[-1] = ' '; value[-1] = '='; break; } } \/* Apply SMTP rewriting then extract the working address. Don't allow \"<>\" as a recipient address *\/ recipient = rewrite_existflags & rewrite_smtp ? rewrite_one(smtp_cmd_data, rewrite_smtp, NULL, FALSE, US\"\", global_rewrite_rules) : smtp_cmd_data; if (!(recipient = parse_extract_address(recipient, &errmess, &start, &end, &recipient_domain, FALSE))) { done = synprot_error(L_smtp_syntax_error, 501, smtp_cmd_data, errmess); rcpt_fail_count++; break; } \/* If the recipient address is unqualified, reject it, unless this is a locally generated message. However, unqualified addresses are permitted from a configured list of hosts and nets - typically when behaving as MUAs rather than MTAs. Sad that SMTP is used for both types of traffic, really. The flag is set at the start of the SMTP connection. RFC 1123 talks about supporting \"the reserved mailbox postmaster\"; I always assumed this meant \"reserved local part\", but the revision of RFC 821 and friends now makes it absolutely clear that it means *mailbox*. Consequently we must always qualify this address, regardless. *\/ if (!recipient_domain) if (!(recipient_domain = qualify_recipient(&recipient, smtp_cmd_data, US\"recipient\"))) { rcpt_fail_count++; break; } \/* Check maximum allowed *\/ if (rcpt_count > recipients_max && recipients_max > 0) { if (recipients_max_reject) { rcpt_fail_count++; smtp_printf(\"552 too many recipients\\r\\n\", FALSE); if (!toomany) log_write(0, LOG_MAIN|LOG_REJECT, \"too many recipients: message \" \"rejected: sender=<%s> %s\", sender_address, host_and_ident(TRUE)); } else { rcpt_defer_count++; smtp_printf(\"452 too many recipients\\r\\n\", FALSE); if (!toomany) log_write(0, LOG_MAIN|LOG_REJECT, \"too many recipients: excess \" \"temporarily rejected: sender=<%s> %s\", sender_address, host_and_ident(TRUE)); } toomany = TRUE; break; } \/* If we have passed the threshold for rate limiting, apply the current delay, and update it for next time, provided this is a limited host. *\/ if (rcpt_count > smtp_rlr_threshold && verify_check_host(&smtp_ratelimit_hosts) == OK) { DEBUG(D_receive) debug_printf(\"rate limit RCPT: delay %.3g sec\\n\", smtp_delay_rcpt\/1000.0); millisleep((int)smtp_delay_rcpt); smtp_delay_rcpt *= smtp_rlr_factor; if (smtp_delay_rcpt > (double)smtp_rlr_limit) smtp_delay_rcpt = (double)smtp_rlr_limit; } \/* If the MAIL ACL discarded all the recipients, we bypass ACL checking for them. Otherwise, check the access control list for this recipient. As there may be a delay in this, re-check for a synchronization error afterwards, unless pipelining was advertised. *\/ if (f.recipients_discarded) rc = DISCARD; else if ( (rc = acl_check(ACL_WHERE_RCPT, recipient, acl_smtp_rcpt, &user_msg, &log_msg)) == OK && !f.smtp_in_pipelining_advertised && !check_sync()) goto SYNC_FAILURE; \/* The ACL was happy *\/ if (rc == OK) { BOOL more = pipeline_response(); if (user_msg) smtp_user_msg(US\"250\", user_msg); else smtp_printf(\"250 Accepted\\r\\n\", more); receive_add_recipient(recipient, -1); \/* Set the dsn flags in the recipients_list *\/ recipients_list[recipients_count-1].orcpt = orcpt; recipients_list[recipients_count-1].dsn_flags = dsn_flags; DEBUG(D_receive) debug_printf(\"DSN: orcpt: %s flags: %d\\n\", recipients_list[recipients_count-1].orcpt, recipients_list[recipients_count-1].dsn_flags); } \/* The recipient was discarded *\/ else if (rc == DISCARD) { if (user_msg) smtp_user_msg(US\"250\", user_msg); else smtp_printf(\"250 Accepted\\r\\n\", FALSE); rcpt_fail_count++; discarded = TRUE; log_write(0, LOG_MAIN|LOG_REJECT, \"%s F=<%s> RCPT %s: \" \"discarded by %s ACL%s%s\", host_and_ident(TRUE), sender_address_unrewritten? sender_address_unrewritten : sender_address, smtp_cmd_argument, f.recipients_discarded? \"MAIL\" : \"RCPT\", log_msg ? US\": \" : US\"\", log_msg ? log_msg : US\"\"); } \/* Either the ACL failed the address, or it was deferred. *\/ else { if (rc == FAIL) rcpt_fail_count++; else rcpt_defer_count++; done = smtp_handle_acl_fail(ACL_WHERE_RCPT, rc, user_msg, log_msg); } break; \/* The DATA command is legal only if it follows successful MAIL FROM and RCPT TO commands. However, if pipelining is advertised, a bad DATA is not counted as a protocol error if it follows RCPT (which must have been rejected if there are no recipients.) This function is complete when a valid DATA command is encountered. Note concerning the code used: RFC 2821 says this: - If there was no MAIL, or no RCPT, command, or all such commands were rejected, the server MAY return a \"command out of sequence\" (503) or \"no valid recipients\" (554) reply in response to the DATA command. The example in the pipelining RFC 2920 uses 554, but I use 503 here because it is the same whether pipelining is in use or not. If all the RCPT commands that precede DATA provoked the same error message (often indicating some kind of system error), it is helpful to include it with the DATA rejection (an idea suggested by Tony Finch). *\/ case BDAT_CMD: { int n; HAD(SCH_BDAT); if (chunking_state != CHUNKING_OFFERED) { done = synprot_error(L_smtp_protocol_error, 503, NULL, US\"BDAT command used when CHUNKING not advertised\"); break; } \/* grab size, endmarker *\/ if (sscanf(CS smtp_cmd_data, \"%u %n\", &chunking_datasize, &n) < 1) { done = synprot_error(L_smtp_protocol_error, 501, NULL, US\"missing size for BDAT command\"); break; } chunking_state = strcmpic(smtp_cmd_data+n, US\"LAST\") == 0 ? CHUNKING_LAST : CHUNKING_ACTIVE; chunking_data_left = chunking_datasize; DEBUG(D_receive) debug_printf(\"chunking state %d, %d bytes\\n\", (int)chunking_state, chunking_data_left); \/* push the current receive_* function on the \"stack\", and replace them by bdat_getc(), which in turn will use the lwr_receive_* functions to do the dirty work. *\/ lwr_receive_getc = receive_getc; lwr_receive_getbuf = receive_getbuf; lwr_receive_ungetc = receive_ungetc; receive_getc = bdat_getc; receive_ungetc = bdat_ungetc; f.dot_ends = FALSE; goto DATA_BDAT; } case DATA_CMD: HAD(SCH_DATA); f.dot_ends = TRUE; DATA_BDAT: \/* Common code for DATA and BDAT *\/ #ifdef EXPERIMENTAL_PIPE_CONNECT fl.pipe_connect_acceptable = FALSE; #endif if (!discarded && recipients_count <= 0) { if (fl.rcpt_smtp_response_same && rcpt_smtp_response != NULL) { uschar *code = US\"503\"; int len = Ustrlen(rcpt_smtp_response); smtp_respond(code, 3, FALSE, US\"All RCPT commands were rejected with \" \"this error:\"); \/* Responses from smtp_printf() will have \\r\\n on the end *\/ if (len > 2 && rcpt_smtp_response[len-2] == '\\r') rcpt_smtp_response[len-2] = 0; smtp_respond(code, 3, FALSE, rcpt_smtp_response); } if (f.smtp_in_pipelining_advertised && last_was_rcpt) smtp_printf(\"503 Valid RCPT command must precede %s\\r\\n\", FALSE, smtp_names[smtp_connection_had[smtp_ch_index-1]]); else done = synprot_error(L_smtp_protocol_error, 503, NULL, smtp_connection_had[smtp_ch_index-1] == SCH_DATA ? US\"valid RCPT command must precede DATA\" : US\"valid RCPT command must precede BDAT\"); if (chunking_state > CHUNKING_OFFERED) bdat_flush_data(); break; } if (toomany && recipients_max_reject) { sender_address = NULL; \/* This will allow a new MAIL without RSET *\/ sender_address_unrewritten = NULL; smtp_printf(\"554 Too many recipients\\r\\n\", FALSE); break; } if (chunking_state > CHUNKING_OFFERED) rc = OK; \/* No predata ACL or go-ahead output for BDAT *\/ else { \/* If there is an ACL, re-check the synchronization afterwards, since the ACL may have delayed. To handle cutthrough delivery enforce a dummy call to get the DATA command sent. *\/ if (acl_smtp_predata == NULL && cutthrough.cctx.sock < 0) rc = OK; else { uschar * acl = acl_smtp_predata ? acl_smtp_predata : US\"accept\"; f.enable_dollar_recipients = TRUE; rc = acl_check(ACL_WHERE_PREDATA, NULL, acl, &user_msg, &log_msg); f.enable_dollar_recipients = FALSE; if (rc == OK && !check_sync()) goto SYNC_FAILURE; if (rc != OK) { \/* Either the ACL failed the address, or it was deferred. *\/ done = smtp_handle_acl_fail(ACL_WHERE_PREDATA, rc, user_msg, log_msg); break; } } if (user_msg) smtp_user_msg(US\"354\", user_msg); else smtp_printf( \"354 Enter message, ending with \\\".\\\" on a line by itself\\r\\n\", FALSE); } #ifdef TCP_QUICKACK if (smtp_in) \/* all ACKs needed to ramp window up for bulk data *\/ (void) setsockopt(fileno(smtp_in), IPPROTO_TCP, TCP_QUICKACK, US &on, sizeof(on)); #endif done = 3; message_ended = END_NOTENDED; \/* Indicate in middle of data *\/ break; case VRFY_CMD: { uschar * address; HAD(SCH_VRFY); if (!(address = parse_extract_address(smtp_cmd_data, &errmess, &start, &end, &recipient_domain, FALSE))) { smtp_printf(\"501 %s\\r\\n\", FALSE, errmess); break; } if (!recipient_domain) if (!(recipient_domain = qualify_recipient(&address, smtp_cmd_data, US\"verify\"))) break; if ((rc = acl_check(ACL_WHERE_VRFY, address, acl_smtp_vrfy, &user_msg, &log_msg)) != OK) done = smtp_handle_acl_fail(ACL_WHERE_VRFY, rc, user_msg, log_msg); else { uschar * s = NULL; address_item * addr = deliver_make_addr(address, FALSE); switch(verify_address(addr, NULL, vopt_is_recipient | vopt_qualify, -1, -1, -1, NULL, NULL, NULL)) { case OK: s = string_sprintf(\"250 <%s> is deliverable\", address); break; case DEFER: s = (addr->user_message != NULL)? string_sprintf(\"451 <%s> %s\", address, addr->user_message) : string_sprintf(\"451 Cannot resolve <%s> at this time\", address); break; case FAIL: s = (addr->user_message != NULL)? string_sprintf(\"550 <%s> %s\", address, addr->user_message) : string_sprintf(\"550 <%s> is not deliverable\", address); log_write(0, LOG_MAIN, \"VRFY failed for %s %s\", smtp_cmd_argument, host_and_ident(TRUE)); break; } smtp_printf(\"%s\\r\\n\", FALSE, s); } break; } case EXPN_CMD: HAD(SCH_EXPN); rc = acl_check(ACL_WHERE_EXPN, NULL, acl_smtp_expn, &user_msg, &log_msg); if (rc != OK) done = smtp_handle_acl_fail(ACL_WHERE_EXPN, rc, user_msg, log_msg); else { BOOL save_log_testing_mode = f.log_testing_mode; f.address_test_mode = f.log_testing_mode = TRUE; (void) verify_address(deliver_make_addr(smtp_cmd_data, FALSE), smtp_out, vopt_is_recipient | vopt_qualify | vopt_expn, -1, -1, -1, NULL, NULL, NULL); f.address_test_mode = FALSE; f.log_testing_mode = save_log_testing_mode; \/* true for -bh *\/ } break; #ifdef SUPPORT_TLS case STARTTLS_CMD: HAD(SCH_STARTTLS); if (!fl.tls_advertised) { done = synprot_error(L_smtp_protocol_error, 503, NULL, US\"STARTTLS command used when not advertised\"); break; } \/* Apply an ACL check if one is defined *\/ if ( acl_smtp_starttls && (rc = acl_check(ACL_WHERE_STARTTLS, NULL, acl_smtp_starttls, &user_msg, &log_msg)) != OK ) { done = smtp_handle_acl_fail(ACL_WHERE_STARTTLS, rc, user_msg, log_msg); break; } \/* RFC 2487 is not clear on when this command may be sent, though it does state that all information previously obtained from the client must be discarded if a TLS session is started. It seems reasonable to do an implied RSET when STARTTLS is received. *\/ incomplete_transaction_log(US\"STARTTLS\"); cancel_cutthrough_connection(TRUE, US\"STARTTLS received\"); smtp_reset(reset_point); toomany = FALSE; cmd_list[CMD_LIST_STARTTLS].is_mail_cmd = FALSE; \/* There's an attack where more data is read in past the STARTTLS command before TLS is negotiated, then assumed to be part of the secure session when used afterwards; we use segregated input buffers, so are not vulnerable, but we want to note when it happens and, for sheer paranoia, ensure that the buffer is \"wiped\". Pipelining sync checks will normally have protected us too, unless disabled by configuration. *\/ if (receive_smtp_buffered()) { DEBUG(D_any) debug_printf(\"Non-empty input buffer after STARTTLS; naive attack?\\n\"); if (tls_in.active.sock < 0) smtp_inend = smtp_inptr = smtp_inbuffer; \/* and if TLS is already active, tls_server_start() should fail *\/ } \/* There is nothing we value in the input buffer and if TLS is successfully negotiated, we won't use this buffer again; if TLS fails, we'll just read fresh content into it. The buffer contains arbitrary content from an untrusted remote source; eg: NOOP \\r\\nSTARTTLS\\r\\n It seems safest to just wipe away the content rather than leave it as a target to jump to. *\/ memset(smtp_inbuffer, 0, IN_BUFFER_SIZE); \/* Attempt to start up a TLS session, and if successful, discard all knowledge that was obtained previously. At least, that's what the RFC says, and that's what happens by default. However, in order to work round YAEB, there is an option to remember the esmtp state. Sigh. We must allow for an extra EHLO command and an extra AUTH command after STARTTLS that don't add to the nonmail command count. *\/ s = NULL; if ((rc = tls_server_start(tls_require_ciphers, &s)) == OK) { if (!tls_remember_esmtp) fl.helo_seen = fl.esmtp = fl.auth_advertised = f.smtp_in_pipelining_advertised = FALSE; cmd_list[CMD_LIST_EHLO].is_mail_cmd = TRUE; cmd_list[CMD_LIST_AUTH].is_mail_cmd = TRUE; cmd_list[CMD_LIST_TLS_AUTH].is_mail_cmd = TRUE; if (sender_helo_name) { store_free(sender_helo_name); sender_helo_name = NULL; host_build_sender_fullhost(); \/* Rebuild *\/ set_process_info(\"handling incoming TLS connection from %s\", host_and_ident(FALSE)); } received_protocol = (sender_host_address ? protocols : protocols_local) [ (fl.esmtp ? pextend + (sender_host_authenticated ? pauthed : 0) : pnormal) + (tls_in.active.sock >= 0 ? pcrpted : 0) ]; sender_host_auth_pubname = sender_host_authenticated = NULL; authenticated_id = NULL; sync_cmd_limit = NON_SYNC_CMD_NON_PIPELINING; DEBUG(D_tls) debug_printf(\"TLS active\\n\"); break; \/* Successful STARTTLS *\/ } else (void) smtp_log_tls_fail(s); \/* Some local configuration problem was discovered before actually trying to do a TLS handshake; give a temporary error. *\/ if (rc == DEFER) { smtp_printf(\"454 TLS currently unavailable\\r\\n\", FALSE); break; } \/* Hard failure. Reject everything except QUIT or closed connection. One cause for failure is a nested STARTTLS, in which case tls_in.active remains set, but we must still reject all incoming commands. Another is a handshake failure - and there may some encrypted data still in the pipe to us, which we see as garbage commands. *\/ DEBUG(D_tls) debug_printf(\"TLS failed to start\\n\"); while (done <= 0) switch(smtp_read_command(FALSE, GETC_BUFFER_UNLIMITED)) { case EOF_CMD: log_write(L_smtp_connection, LOG_MAIN, \"%s closed by EOF\", smtp_get_connection_info()); smtp_notquit_exit(US\"tls-failed\", NULL, NULL); done = 2; break; \/* It is perhaps arguable as to which exit ACL should be called here, but as it is probably a situation that almost never arises, it probably doesn't matter. We choose to call the real QUIT ACL, which in some sense is perhaps \"right\". *\/ case QUIT_CMD: user_msg = NULL; if ( acl_smtp_quit && ((rc = acl_check(ACL_WHERE_QUIT, NULL, acl_smtp_quit, &user_msg, &log_msg)) == ERROR)) log_write(0, LOG_MAIN|LOG_PANIC, \"ACL for QUIT returned ERROR: %s\", log_msg); if (user_msg) smtp_respond(US\"221\", 3, TRUE, user_msg); else smtp_printf(\"221 %s closing connection\\r\\n\", FALSE, smtp_active_hostname); log_write(L_smtp_connection, LOG_MAIN, \"%s closed by QUIT\", smtp_get_connection_info()); done = 2; break; default: smtp_printf(\"554 Security failure\\r\\n\", FALSE); break; } tls_close(NULL, TLS_SHUTDOWN_NOWAIT); break; #endif \/* The ACL for QUIT is provided for gathering statistical information or similar; it does not affect the response code, but it can supply a custom message. *\/ case QUIT_CMD: smtp_quit_handler(&user_msg, &log_msg); done = 2; break; case RSET_CMD: smtp_rset_handler(); cancel_cutthrough_connection(TRUE, US\"RSET received\"); smtp_reset(reset_point); toomany = FALSE; break; case NOOP_CMD: HAD(SCH_NOOP); smtp_printf(\"250 OK\\r\\n\", FALSE); break; \/* Show ETRN\/EXPN\/VRFY if there's an ACL for checking hosts; if actually used, a check will be done for permitted hosts. Show STARTTLS only if not already in a TLS session and if it would be advertised in the EHLO response. *\/ case HELP_CMD: HAD(SCH_HELP); smtp_printf(\"214-Commands supported:\\r\\n\", TRUE); { uschar buffer[256]; buffer[0] = 0; Ustrcat(buffer, \" AUTH\"); #ifdef SUPPORT_TLS if (tls_in.active.sock < 0 && verify_check_host(&tls_advertise_hosts) != FAIL) Ustrcat(buffer, \" STARTTLS\"); #endif Ustrcat(buffer, \" HELO EHLO MAIL RCPT DATA BDAT\"); Ustrcat(buffer, \" NOOP QUIT RSET HELP\"); if (acl_smtp_etrn != NULL) Ustrcat(buffer, \" ETRN\"); if (acl_smtp_expn != NULL) Ustrcat(buffer, \" EXPN\"); if (acl_smtp_vrfy != NULL) Ustrcat(buffer, \" VRFY\"); smtp_printf(\"214%s\\r\\n\", FALSE, buffer); } break; case EOF_CMD: incomplete_transaction_log(US\"connection lost\"); smtp_notquit_exit(US\"connection-lost\", US\"421\", US\"%s lost input connection\", smtp_active_hostname); \/* Don't log by default unless in the middle of a message, as some mailers just drop the call rather than sending QUIT, and it clutters up the logs. *\/ if (sender_address || recipients_count > 0) log_write(L_lost_incoming_connection, LOG_MAIN, \"unexpected %s while reading SMTP command from %s%s%s D=%s\", f.sender_host_unknown ? \"EOF\" : \"disconnection\", f.tcp_in_fastopen_logged ? US\"\" : f.tcp_in_fastopen ? f.tcp_in_fastopen_data ? US\"TFO* \" : US\"TFO \" : US\"\", host_and_ident(FALSE), smtp_read_error, string_timesince(&smtp_connection_start) ); else log_write(L_smtp_connection, LOG_MAIN, \"%s %slost%s D=%s\", smtp_get_connection_info(), f.tcp_in_fastopen && !f.tcp_in_fastopen_logged ? US\"TFO \" : US\"\", smtp_read_error, string_timesince(&smtp_connection_start) ); done = 1; break; case ETRN_CMD: HAD(SCH_ETRN); if (sender_address) { done = synprot_error(L_smtp_protocol_error, 503, NULL, US\"ETRN is not permitted inside a transaction\"); break; } log_write(L_etrn, LOG_MAIN, \"ETRN %s received from %s\", smtp_cmd_argument, host_and_ident(FALSE)); if ((rc = acl_check(ACL_WHERE_ETRN, NULL, acl_smtp_etrn, &user_msg, &log_msg)) != OK) { done = smtp_handle_acl_fail(ACL_WHERE_ETRN, rc, user_msg, log_msg); break; } \/* Compute the serialization key for this command. *\/ etrn_serialize_key = string_sprintf(\"etrn-%s\\n\", smtp_cmd_data); \/* If a command has been specified for running as a result of ETRN, we permit any argument to ETRN. If not, only the # standard form is permitted, since that is strictly the only kind of ETRN that can be implemented according to the RFC. *\/ if (smtp_etrn_command) { uschar *error; BOOL rc; etrn_command = smtp_etrn_command; deliver_domain = smtp_cmd_data; rc = transport_set_up_command(&argv, smtp_etrn_command, TRUE, 0, NULL, US\"ETRN processing\", &error); deliver_domain = NULL; if (!rc) { log_write(0, LOG_MAIN|LOG_PANIC, \"failed to set up ETRN command: %s\", error); smtp_printf(\"458 Internal failure\\r\\n\", FALSE); break; } } \/* Else set up to call Exim with the -R option. *\/ else { if (*smtp_cmd_data++ != '#') { done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"argument must begin with #\"); break; } etrn_command = US\"exim -R\"; argv = CUSS child_exec_exim(CEE_RETURN_ARGV, TRUE, NULL, TRUE, *queue_name ? 4 : 2, US\"-R\", smtp_cmd_data, US\"-MCG\", queue_name); } \/* If we are host-testing, don't actually do anything. *\/ if (host_checking) { HDEBUG(D_any) { debug_printf(\"ETRN command is: %s\\n\", etrn_command); debug_printf(\"ETRN command execution skipped\\n\"); } if (user_msg == NULL) smtp_printf(\"250 OK\\r\\n\", FALSE); else smtp_user_msg(US\"250\", user_msg); break; } \/* If ETRN queue runs are to be serialized, check the database to ensure one isn't already running. *\/ if (smtp_etrn_serialize && !enq_start(etrn_serialize_key, 1)) { smtp_printf(\"458 Already processing %s\\r\\n\", FALSE, smtp_cmd_data); break; } \/* Fork a child process and run the command. We don't want to have to wait for the process at any point, so set SIGCHLD to SIG_IGN before forking. It should be set that way anyway for external incoming SMTP, but we save and restore to be tidy. If serialization is required, we actually run the command in yet another process, so we can wait for it to complete and then remove the serialization lock. *\/ oldsignal = signal(SIGCHLD, SIG_IGN); if ((pid = fork()) == 0) { smtp_input = FALSE; \/* This process is not associated with the *\/ (void)fclose(smtp_in); \/* SMTP call any more. *\/ (void)fclose(smtp_out); signal(SIGCHLD, SIG_DFL); \/* Want to catch child *\/ \/* If not serializing, do the exec right away. Otherwise, fork down into another process. *\/ if (!smtp_etrn_serialize || (pid = fork()) == 0) { DEBUG(D_exec) debug_print_argv(argv); exim_nullstd(); \/* Ensure std{in,out,err} exist *\/ execv(CS argv[0], (char *const *)argv); log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"exec of \\\"%s\\\" (ETRN) failed: %s\", etrn_command, strerror(errno)); _exit(EXIT_FAILURE); \/* paranoia *\/ } \/* Obey this if smtp_serialize and the 2nd fork yielded non-zero. That is, we are in the first subprocess, after forking again. All we can do for a failing fork is to log it. Otherwise, wait for the 2nd process to complete, before removing the serialization. *\/ if (pid < 0) log_write(0, LOG_MAIN|LOG_PANIC, \"2nd fork for serialized ETRN \" \"failed: %s\", strerror(errno)); else { int status; DEBUG(D_any) debug_printf(\"waiting for serialized ETRN process %d\\n\", (int)pid); (void)wait(&status); DEBUG(D_any) debug_printf(\"serialized ETRN process %d ended\\n\", (int)pid); } enq_end(etrn_serialize_key); _exit(EXIT_SUCCESS); } \/* Back in the top level SMTP process. Check that we started a subprocess and restore the signal state. *\/ if (pid < 0) { log_write(0, LOG_MAIN|LOG_PANIC, \"fork of process for ETRN failed: %s\", strerror(errno)); smtp_printf(\"458 Unable to fork process\\r\\n\", FALSE); if (smtp_etrn_serialize) enq_end(etrn_serialize_key); } else { if (user_msg == NULL) smtp_printf(\"250 OK\\r\\n\", FALSE); else smtp_user_msg(US\"250\", user_msg); } signal(SIGCHLD, oldsignal); break; case BADARG_CMD: done = synprot_error(L_smtp_syntax_error, 501, NULL, US\"unexpected argument data\"); break; \/* This currently happens only for NULLs, but could be extended. *\/ case BADCHAR_CMD: done = synprot_error(L_smtp_syntax_error, 0, NULL, \/* Just logs *\/ US\"NUL character(s) present (shown as '?')\"); smtp_printf(\"501 NUL characters are not allowed in SMTP commands\\r\\n\", FALSE); break; case BADSYN_CMD: SYNC_FAILURE: if (smtp_inend >= smtp_inbuffer + IN_BUFFER_SIZE) smtp_inend = smtp_inbuffer + IN_BUFFER_SIZE - 1; c = smtp_inend - smtp_inptr; if (c > 150) c = 150; \/* limit logged amount *\/ smtp_inptr[c] = 0; incomplete_transaction_log(US\"sync failure\"); log_write(0, LOG_MAIN|LOG_REJECT, \"SMTP protocol synchronization error \" \"(next input sent too soon: pipelining was%s advertised): \" \"rejected \\\"%s\\\" %s next input=\\\"%s\\\"\", f.smtp_in_pipelining_advertised ? \"\" : \" not\", smtp_cmd_buffer, host_and_ident(TRUE), string_printing(smtp_inptr)); smtp_notquit_exit(US\"synchronization-error\", US\"554\", US\"SMTP synchronization error\"); done = 1; \/* Pretend eof - drops connection *\/ break; case TOO_MANY_NONMAIL_CMD: s = smtp_cmd_buffer; while (*s != 0 && !isspace(*s)) s++; incomplete_transaction_log(US\"too many non-mail commands\"); log_write(0, LOG_MAIN|LOG_REJECT, \"SMTP call from %s dropped: too many \" \"nonmail commands (last was \\\"%.*s\\\")\", host_and_ident(FALSE), (int)(s - smtp_cmd_buffer), smtp_cmd_buffer); smtp_notquit_exit(US\"bad-commands\", US\"554\", US\"Too many nonmail commands\"); done = 1; \/* Pretend eof - drops connection *\/ break; #ifdef SUPPORT_PROXY case PROXY_FAIL_IGNORE_CMD: smtp_printf(\"503 Command refused, required Proxy negotiation failed\\r\\n\", FALSE); break; #endif default: if (unknown_command_count++ >= smtp_max_unknown_commands) { log_write(L_smtp_syntax_error, LOG_MAIN, \"SMTP syntax error in \\\"%s\\\" %s %s\", string_printing(smtp_cmd_buffer), host_and_ident(TRUE), US\"unrecognized command\"); incomplete_transaction_log(US\"unrecognized command\"); smtp_notquit_exit(US\"bad-commands\", US\"500\", US\"Too many unrecognized commands\"); done = 2; log_write(0, LOG_MAIN|LOG_REJECT, \"SMTP call from %s dropped: too many \" \"unrecognized commands (last was \\\"%s\\\")\", host_and_ident(FALSE), string_printing(smtp_cmd_buffer)); } else done = synprot_error(L_smtp_syntax_error, 500, NULL, US\"unrecognized command\"); break; } \/* This label is used by goto's inside loops that want to break out to the end of the command-processing loop. *\/ COMMAND_LOOP: last_was_rej_mail = was_rej_mail; \/* Remember some last commands for *\/ last_was_rcpt = was_rcpt; \/* protocol error handling *\/ continue; } return done - 2; \/* Convert yield values *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":192773,"input":"static void gen_sse(CPUX86State *env, DisasContext *s, int b, target_ulong pc_start, int rex_r) { int b1, op1_offset, op2_offset, is_xmm, val; int modrm, mod, rm, reg; SSEFunc_0_epp sse_fn_epp; SSEFunc_0_eppi sse_fn_eppi; SSEFunc_0_ppi sse_fn_ppi; SSEFunc_0_eppt sse_fn_eppt; TCGMemOp ot; b &= 0xff; if (s->prefix & PREFIX_DATA) b1 = 1; else if (s->prefix & PREFIX_REPZ) b1 = 2; else if (s->prefix & PREFIX_REPNZ) b1 = 3; else b1 = 0; sse_fn_epp = sse_op_table1[b][b1]; if (!sse_fn_epp) { goto unknown_op; } if ((b <= 0x5f && b >= 0x10) || b == 0xc6 || b == 0xc2) { is_xmm = 1; } else { if (b1 == 0) { \/* MMX case *\/ is_xmm = 0; } else { is_xmm = 1; } } \/* simple MMX\/SSE operation *\/ if (s->flags & HF_TS_MASK) { gen_exception(s, EXCP07_PREX, pc_start - s->cs_base); return; } if (s->flags & HF_EM_MASK) { illegal_op: gen_illegal_opcode(s); return; } if (is_xmm && !(s->flags & HF_OSFXSR_MASK) && ((b != 0x38 && b != 0x3a) || (s->prefix & PREFIX_DATA))) { goto unknown_op; } if (b == 0x0e) { if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW)) { \/* If we were fully decoding this we might use illegal_op. *\/ goto unknown_op; } \/* femms *\/ gen_helper_emms(cpu_env); return; } if (b == 0x77) { \/* emms *\/ gen_helper_emms(cpu_env); return; } \/* prepare MMX state (XXX: optimize by storing fptt and fptags in the static cpu state) *\/ if (!is_xmm) { gen_helper_enter_mmx(cpu_env); } modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7); if (is_xmm) reg |= rex_r; mod = (modrm >> 6) & 3; if (sse_fn_epp == SSE_SPECIAL) { b |= (b1 << 8); switch(b) { case 0x0e7: \/* movntq *\/ if (mod == 3) { goto illegal_op; } gen_lea_modrm(env, s, modrm); gen_stq_env_A0(s, offsetof(CPUX86State, fpregs[reg].mmx)); break; case 0x1e7: \/* movntdq *\/ case 0x02b: \/* movntps *\/ case 0x12b: \/* movntps *\/ if (mod == 3) goto illegal_op; gen_lea_modrm(env, s, modrm); gen_sto_env_A0(s, offsetof(CPUX86State, xmm_regs[reg])); break; case 0x3f0: \/* lddqu *\/ if (mod == 3) goto illegal_op; gen_lea_modrm(env, s, modrm); gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg])); break; case 0x22b: \/* movntss *\/ case 0x32b: \/* movntsd *\/ if (mod == 3) goto illegal_op; gen_lea_modrm(env, s, modrm); if (b1 & 1) { gen_stq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(0))); } else { tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_L(0))); gen_op_st_v(s, MO_32, cpu_T0, cpu_A0); } break; case 0x6e: \/* movd mm, ea *\/ #ifdef TARGET_X86_64 if (s->dflag == MO_64) { gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 0); tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State,fpregs[reg].mmx)); } else #endif { gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 0); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,fpregs[reg].mmx)); tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); gen_helper_movl_mm_T0_mmx(cpu_ptr0, cpu_tmp2_i32); } break; case 0x16e: \/* movd xmm, ea *\/ #ifdef TARGET_X86_64 if (s->dflag == MO_64) { gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 0); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[reg])); gen_helper_movq_mm_T0_xmm(cpu_ptr0, cpu_T0); } else #endif { gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 0); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[reg])); tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); gen_helper_movl_mm_T0_xmm(cpu_ptr0, cpu_tmp2_i32); } break; case 0x6f: \/* movq mm, ea *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_ldq_env_A0(s, offsetof(CPUX86State, fpregs[reg].mmx)); } else { rm = (modrm & 7); tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offsetof(CPUX86State,fpregs[rm].mmx)); tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offsetof(CPUX86State,fpregs[reg].mmx)); } break; case 0x010: \/* movups *\/ case 0x110: \/* movupd *\/ case 0x028: \/* movaps *\/ case 0x128: \/* movapd *\/ case 0x16f: \/* movdqa xmm, ea *\/ case 0x26f: \/* movdqu xmm, ea *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg])); } else { rm = (modrm & 7) | REX_B(s); gen_op_movo(offsetof(CPUX86State,xmm_regs[reg]), offsetof(CPUX86State,xmm_regs[rm])); } break; case 0x210: \/* movss xmm, ea *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_op_ld_v(s, MO_32, cpu_T0, cpu_A0); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0))); tcg_gen_movi_tl(cpu_T0, 0); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1))); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2))); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3))); } else { rm = (modrm & 7) | REX_B(s); gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)), offsetof(CPUX86State,xmm_regs[rm].ZMM_L(0))); } break; case 0x310: \/* movsd xmm, ea *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(0))); tcg_gen_movi_tl(cpu_T0, 0); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2))); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3))); } else { rm = (modrm & 7) | REX_B(s); gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)), offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0))); } break; case 0x012: \/* movlps *\/ case 0x112: \/* movlpd *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(0))); } else { \/* movhlps *\/ rm = (modrm & 7) | REX_B(s); gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)), offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(1))); } break; case 0x212: \/* movsldup *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg])); } else { rm = (modrm & 7) | REX_B(s); gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)), offsetof(CPUX86State,xmm_regs[rm].ZMM_L(0))); gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)), offsetof(CPUX86State,xmm_regs[rm].ZMM_L(2))); } gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)), offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0))); gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)), offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2))); break; case 0x312: \/* movddup *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(0))); } else { rm = (modrm & 7) | REX_B(s); gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)), offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0))); } gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)), offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0))); break; case 0x016: \/* movhps *\/ case 0x116: \/* movhpd *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(1))); } else { \/* movlhps *\/ rm = (modrm & 7) | REX_B(s); gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)), offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0))); } break; case 0x216: \/* movshdup *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg])); } else { rm = (modrm & 7) | REX_B(s); gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)), offsetof(CPUX86State,xmm_regs[rm].ZMM_L(1))); gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)), offsetof(CPUX86State,xmm_regs[rm].ZMM_L(3))); } gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)), offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1))); gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)), offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3))); break; case 0x178: case 0x378: { int bit_index, field_length; if (b1 == 1 && reg != 0) goto illegal_op; field_length = cpu_ldub_code(env, s->pc++) & 0x3F; bit_index = cpu_ldub_code(env, s->pc++) & 0x3F; tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[reg])); if (b1 == 1) gen_helper_extrq_i(cpu_env, cpu_ptr0, tcg_const_i32(bit_index), tcg_const_i32(field_length)); else gen_helper_insertq_i(cpu_env, cpu_ptr0, tcg_const_i32(bit_index), tcg_const_i32(field_length)); } break; case 0x7e: \/* movd ea, mm *\/ #ifdef TARGET_X86_64 if (s->dflag == MO_64) { tcg_gen_ld_i64(cpu_T0, cpu_env, offsetof(CPUX86State,fpregs[reg].mmx)); gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 1); } else #endif { tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,fpregs[reg].mmx.MMX_L(0))); gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 1); } break; case 0x17e: \/* movd ea, xmm *\/ #ifdef TARGET_X86_64 if (s->dflag == MO_64) { tcg_gen_ld_i64(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0))); gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 1); } else #endif { tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0))); gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 1); } break; case 0x27e: \/* movq xmm, ea *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(0))); } else { rm = (modrm & 7) | REX_B(s); gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)), offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0))); } gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1))); break; case 0x7f: \/* movq ea, mm *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_stq_env_A0(s, offsetof(CPUX86State, fpregs[reg].mmx)); } else { rm = (modrm & 7); gen_op_movq(offsetof(CPUX86State,fpregs[rm].mmx), offsetof(CPUX86State,fpregs[reg].mmx)); } break; case 0x011: \/* movups *\/ case 0x111: \/* movupd *\/ case 0x029: \/* movaps *\/ case 0x129: \/* movapd *\/ case 0x17f: \/* movdqa ea, xmm *\/ case 0x27f: \/* movdqu ea, xmm *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_sto_env_A0(s, offsetof(CPUX86State, xmm_regs[reg])); } else { rm = (modrm & 7) | REX_B(s); gen_op_movo(offsetof(CPUX86State,xmm_regs[rm]), offsetof(CPUX86State,xmm_regs[reg])); } break; case 0x211: \/* movss ea, xmm *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0))); gen_op_st_v(s, MO_32, cpu_T0, cpu_A0); } else { rm = (modrm & 7) | REX_B(s); gen_op_movl(offsetof(CPUX86State,xmm_regs[rm].ZMM_L(0)), offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0))); } break; case 0x311: \/* movsd ea, xmm *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_stq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(0))); } else { rm = (modrm & 7) | REX_B(s); gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)), offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0))); } break; case 0x013: \/* movlps *\/ case 0x113: \/* movlpd *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_stq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(0))); } else { goto illegal_op; } break; case 0x017: \/* movhps *\/ case 0x117: \/* movhpd *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_stq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(1))); } else { goto illegal_op; } break; case 0x71: \/* shift mm, im *\/ case 0x72: case 0x73: case 0x171: \/* shift xmm, im *\/ case 0x172: case 0x173: if (b1 >= 2) { goto unknown_op; } val = cpu_ldub_code(env, s->pc++); if (is_xmm) { tcg_gen_movi_tl(cpu_T0, val); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(0))); tcg_gen_movi_tl(cpu_T0, 0); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(1))); op1_offset = offsetof(CPUX86State,xmm_t0); } else { tcg_gen_movi_tl(cpu_T0, val); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(0))); tcg_gen_movi_tl(cpu_T0, 0); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(1))); op1_offset = offsetof(CPUX86State,mmx_t0); } sse_fn_epp = sse_op_table2[((b - 1) & 3) * 8 + (((modrm >> 3)) & 7)][b1]; if (!sse_fn_epp) { goto unknown_op; } if (is_xmm) { rm = (modrm & 7) | REX_B(s); op2_offset = offsetof(CPUX86State,xmm_regs[rm]); } else { rm = (modrm & 7); op2_offset = offsetof(CPUX86State,fpregs[rm].mmx); } tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op1_offset); sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1); break; case 0x050: \/* movmskps *\/ rm = (modrm & 7) | REX_B(s); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[rm])); gen_helper_movmskps(cpu_tmp2_i32, cpu_env, cpu_ptr0); tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32); break; case 0x150: \/* movmskpd *\/ rm = (modrm & 7) | REX_B(s); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[rm])); gen_helper_movmskpd(cpu_tmp2_i32, cpu_env, cpu_ptr0); tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32); break; case 0x02a: \/* cvtpi2ps *\/ case 0x12a: \/* cvtpi2pd *\/ gen_helper_enter_mmx(cpu_env); if (mod != 3) { gen_lea_modrm(env, s, modrm); op2_offset = offsetof(CPUX86State,mmx_t0); gen_ldq_env_A0(s, op2_offset); } else { rm = (modrm & 7); op2_offset = offsetof(CPUX86State,fpregs[rm].mmx); } op1_offset = offsetof(CPUX86State,xmm_regs[reg]); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset); switch(b >> 8) { case 0x0: gen_helper_cvtpi2ps(cpu_env, cpu_ptr0, cpu_ptr1); break; default: case 0x1: gen_helper_cvtpi2pd(cpu_env, cpu_ptr0, cpu_ptr1); break; } break; case 0x22a: \/* cvtsi2ss *\/ case 0x32a: \/* cvtsi2sd *\/ ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); op1_offset = offsetof(CPUX86State,xmm_regs[reg]); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); if (ot == MO_32) { SSEFunc_0_epi sse_fn_epi = sse_op_table3ai[(b >> 8) & 1]; tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); sse_fn_epi(cpu_env, cpu_ptr0, cpu_tmp2_i32); } else { #ifdef TARGET_X86_64 SSEFunc_0_epl sse_fn_epl = sse_op_table3aq[(b >> 8) & 1]; sse_fn_epl(cpu_env, cpu_ptr0, cpu_T0); #else goto illegal_op; #endif } break; case 0x02c: \/* cvttps2pi *\/ case 0x12c: \/* cvttpd2pi *\/ case 0x02d: \/* cvtps2pi *\/ case 0x12d: \/* cvtpd2pi *\/ gen_helper_enter_mmx(cpu_env); if (mod != 3) { gen_lea_modrm(env, s, modrm); op2_offset = offsetof(CPUX86State,xmm_t0); gen_ldo_env_A0(s, op2_offset); } else { rm = (modrm & 7) | REX_B(s); op2_offset = offsetof(CPUX86State,xmm_regs[rm]); } op1_offset = offsetof(CPUX86State,fpregs[reg & 7].mmx); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset); switch(b) { case 0x02c: gen_helper_cvttps2pi(cpu_env, cpu_ptr0, cpu_ptr1); break; case 0x12c: gen_helper_cvttpd2pi(cpu_env, cpu_ptr0, cpu_ptr1); break; case 0x02d: gen_helper_cvtps2pi(cpu_env, cpu_ptr0, cpu_ptr1); break; case 0x12d: gen_helper_cvtpd2pi(cpu_env, cpu_ptr0, cpu_ptr1); break; } break; case 0x22c: \/* cvttss2si *\/ case 0x32c: \/* cvttsd2si *\/ case 0x22d: \/* cvtss2si *\/ case 0x32d: \/* cvtsd2si *\/ ot = mo_64_32(s->dflag); if (mod != 3) { gen_lea_modrm(env, s, modrm); if ((b >> 8) & 1) { gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_t0.ZMM_Q(0))); } else { gen_op_ld_v(s, MO_32, cpu_T0, cpu_A0); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(0))); } op2_offset = offsetof(CPUX86State,xmm_t0); } else { rm = (modrm & 7) | REX_B(s); op2_offset = offsetof(CPUX86State,xmm_regs[rm]); } tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset); if (ot == MO_32) { SSEFunc_i_ep sse_fn_i_ep = sse_op_table3bi[((b >> 7) & 2) | (b & 1)]; sse_fn_i_ep(cpu_tmp2_i32, cpu_env, cpu_ptr0); tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32); } else { #ifdef TARGET_X86_64 SSEFunc_l_ep sse_fn_l_ep = sse_op_table3bq[((b >> 7) & 2) | (b & 1)]; sse_fn_l_ep(cpu_T0, cpu_env, cpu_ptr0); #else goto illegal_op; #endif } gen_op_mov_reg_v(ot, reg, cpu_T0); break; case 0xc4: \/* pinsrw *\/ case 0x1c4: s->rip_offset = 1; gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0); val = cpu_ldub_code(env, s->pc++); if (b1) { val &= 7; tcg_gen_st16_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_W(val))); } else { val &= 3; tcg_gen_st16_tl(cpu_T0, cpu_env, offsetof(CPUX86State,fpregs[reg].mmx.MMX_W(val))); } break; case 0xc5: \/* pextrw *\/ case 0x1c5: if (mod != 3) goto illegal_op; ot = mo_64_32(s->dflag); val = cpu_ldub_code(env, s->pc++); if (b1) { val &= 7; rm = (modrm & 7) | REX_B(s); tcg_gen_ld16u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[rm].ZMM_W(val))); } else { val &= 3; rm = (modrm & 7); tcg_gen_ld16u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,fpregs[rm].mmx.MMX_W(val))); } reg = ((modrm >> 3) & 7) | rex_r; gen_op_mov_reg_v(ot, reg, cpu_T0); break; case 0x1d6: \/* movq ea, xmm *\/ if (mod != 3) { gen_lea_modrm(env, s, modrm); gen_stq_env_A0(s, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(0))); } else { rm = (modrm & 7) | REX_B(s); gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)), offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0))); gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(1))); } break; case 0x2d6: \/* movq2dq *\/ gen_helper_enter_mmx(cpu_env); rm = (modrm & 7); gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)), offsetof(CPUX86State,fpregs[rm].mmx)); gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1))); break; case 0x3d6: \/* movdq2q *\/ gen_helper_enter_mmx(cpu_env); rm = (modrm & 7) | REX_B(s); gen_op_movq(offsetof(CPUX86State,fpregs[reg & 7].mmx), offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0))); break; case 0xd7: \/* pmovmskb *\/ case 0x1d7: if (mod != 3) goto illegal_op; if (b1) { rm = (modrm & 7) | REX_B(s); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[rm])); gen_helper_pmovmskb_xmm(cpu_tmp2_i32, cpu_env, cpu_ptr0); } else { rm = (modrm & 7); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,fpregs[rm].mmx)); gen_helper_pmovmskb_mmx(cpu_tmp2_i32, cpu_env, cpu_ptr0); } reg = ((modrm >> 3) & 7) | rex_r; tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32); break; case 0x138: case 0x038: b = modrm; if ((b & 0xf0) == 0xf0) { goto do_0f_38_fx; } modrm = cpu_ldub_code(env, s->pc++); rm = modrm & 7; reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; if (b1 >= 2) { goto unknown_op; } sse_fn_epp = sse_op_table6[b].op[b1]; if (!sse_fn_epp) { goto unknown_op; } if (!(s->cpuid_ext_features & sse_op_table6[b].ext_mask)) goto illegal_op; if (b1) { op1_offset = offsetof(CPUX86State,xmm_regs[reg]); if (mod == 3) { op2_offset = offsetof(CPUX86State,xmm_regs[rm | REX_B(s)]); } else { op2_offset = offsetof(CPUX86State,xmm_t0); gen_lea_modrm(env, s, modrm); switch (b) { case 0x20: case 0x30: \/* pmovsxbw, pmovzxbw *\/ case 0x23: case 0x33: \/* pmovsxwd, pmovzxwd *\/ case 0x25: case 0x35: \/* pmovsxdq, pmovzxdq *\/ gen_ldq_env_A0(s, op2_offset + offsetof(ZMMReg, ZMM_Q(0))); break; case 0x21: case 0x31: \/* pmovsxbd, pmovzxbd *\/ case 0x24: case 0x34: \/* pmovsxwq, pmovzxwq *\/ tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, op2_offset + offsetof(ZMMReg, ZMM_L(0))); break; case 0x22: case 0x32: \/* pmovsxbq, pmovzxbq *\/ tcg_gen_qemu_ld_tl(cpu_tmp0, cpu_A0, s->mem_index, MO_LEUW); tcg_gen_st16_tl(cpu_tmp0, cpu_env, op2_offset + offsetof(ZMMReg, ZMM_W(0))); break; case 0x2a: \/* movntqda *\/ gen_ldo_env_A0(s, op1_offset); return; default: gen_ldo_env_A0(s, op2_offset); } } } else { op1_offset = offsetof(CPUX86State,fpregs[reg].mmx); if (mod == 3) { op2_offset = offsetof(CPUX86State,fpregs[rm].mmx); } else { op2_offset = offsetof(CPUX86State,mmx_t0); gen_lea_modrm(env, s, modrm); gen_ldq_env_A0(s, op2_offset); } } if (sse_fn_epp == SSE_SPECIAL) { goto unknown_op; } tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset); sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1); if (b == 0x17) { set_cc_op(s, CC_OP_EFLAGS); } break; case 0x238: case 0x338: do_0f_38_fx: \/* Various integer extensions at 0f 38 f[0-f]. *\/ b = modrm | (b1 << 8); modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; switch (b) { case 0x3f0: \/* crc32 Gd,Eb *\/ case 0x3f1: \/* crc32 Gd,Ey *\/ do_crc32: if (!(s->cpuid_ext_features & CPUID_EXT_SSE42)) { goto illegal_op; } if ((b & 0xff) == 0xf0) { ot = MO_8; } else if (s->dflag != MO_64) { ot = (s->prefix & PREFIX_DATA ? MO_16 : MO_32); } else { ot = MO_64; } tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[reg]); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); gen_helper_crc32(cpu_T0, cpu_tmp2_i32, cpu_T0, tcg_const_i32(8 << ot)); ot = mo_64_32(s->dflag); gen_op_mov_reg_v(ot, reg, cpu_T0); break; case 0x1f0: \/* crc32 or movbe *\/ case 0x1f1: \/* For these insns, the f3 prefix is supposed to have priority over the 66 prefix, but that's not what we implement above setting b1. *\/ if (s->prefix & PREFIX_REPNZ) { goto do_crc32; } \/* FALLTHRU *\/ case 0x0f0: \/* movbe Gy,My *\/ case 0x0f1: \/* movbe My,Gy *\/ if (!(s->cpuid_ext_features & CPUID_EXT_MOVBE)) { goto illegal_op; } if (s->dflag != MO_64) { ot = (s->prefix & PREFIX_DATA ? MO_16 : MO_32); } else { ot = MO_64; } gen_lea_modrm(env, s, modrm); if ((b & 1) == 0) { tcg_gen_qemu_ld_tl(cpu_T0, cpu_A0, s->mem_index, ot | MO_BE); gen_op_mov_reg_v(ot, reg, cpu_T0); } else { tcg_gen_qemu_st_tl(cpu_regs[reg], cpu_A0, s->mem_index, ot | MO_BE); } break; case 0x0f2: \/* andn Gy, By, Ey *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1) || !(s->prefix & PREFIX_VEX) || s->vex_l != 0) { goto illegal_op; } ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); tcg_gen_andc_tl(cpu_T0, cpu_regs[s->vex_v], cpu_T0); gen_op_mov_reg_v(ot, reg, cpu_T0); gen_op_update1_cc(); set_cc_op(s, CC_OP_LOGICB + ot); break; case 0x0f7: \/* bextr Gy, Ey, By *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1) || !(s->prefix & PREFIX_VEX) || s->vex_l != 0) { goto illegal_op; } ot = mo_64_32(s->dflag); { TCGv bound, zero; gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); \/* Extract START, and shift the operand. Shifts larger than operand size get zeros. *\/ tcg_gen_ext8u_tl(cpu_A0, cpu_regs[s->vex_v]); tcg_gen_shr_tl(cpu_T0, cpu_T0, cpu_A0); bound = tcg_const_tl(ot == MO_64 ? 63 : 31); zero = tcg_const_tl(0); tcg_gen_movcond_tl(TCG_COND_LEU, cpu_T0, cpu_A0, bound, cpu_T0, zero); tcg_temp_free(zero); \/* Extract the LEN into a mask. Lengths larger than operand size get all ones. *\/ tcg_gen_extract_tl(cpu_A0, cpu_regs[s->vex_v], 8, 8); tcg_gen_movcond_tl(TCG_COND_LEU, cpu_A0, cpu_A0, bound, cpu_A0, bound); tcg_temp_free(bound); tcg_gen_movi_tl(cpu_T1, 1); tcg_gen_shl_tl(cpu_T1, cpu_T1, cpu_A0); tcg_gen_subi_tl(cpu_T1, cpu_T1, 1); tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_T1); gen_op_mov_reg_v(ot, reg, cpu_T0); gen_op_update1_cc(); set_cc_op(s, CC_OP_LOGICB + ot); } break; case 0x0f5: \/* bzhi Gy, Ey, By *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2) || !(s->prefix & PREFIX_VEX) || s->vex_l != 0) { goto illegal_op; } ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); tcg_gen_ext8u_tl(cpu_T1, cpu_regs[s->vex_v]); { TCGv bound = tcg_const_tl(ot == MO_64 ? 63 : 31); \/* Note that since we're using BMILG (in order to get O cleared) we need to store the inverse into C. *\/ tcg_gen_setcond_tl(TCG_COND_LT, cpu_cc_src, cpu_T1, bound); tcg_gen_movcond_tl(TCG_COND_GT, cpu_T1, cpu_T1, bound, bound, cpu_T1); tcg_temp_free(bound); } tcg_gen_movi_tl(cpu_A0, -1); tcg_gen_shl_tl(cpu_A0, cpu_A0, cpu_T1); tcg_gen_andc_tl(cpu_T0, cpu_T0, cpu_A0); gen_op_mov_reg_v(ot, reg, cpu_T0); gen_op_update1_cc(); set_cc_op(s, CC_OP_BMILGB + ot); break; case 0x3f6: \/* mulx By, Gy, rdx, Ey *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2) || !(s->prefix & PREFIX_VEX) || s->vex_l != 0) { goto illegal_op; } ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); switch (ot) { default: tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_regs[R_EDX]); tcg_gen_mulu2_i32(cpu_tmp2_i32, cpu_tmp3_i32, cpu_tmp2_i32, cpu_tmp3_i32); tcg_gen_extu_i32_tl(cpu_regs[s->vex_v], cpu_tmp2_i32); tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp3_i32); break; #ifdef TARGET_X86_64 case MO_64: tcg_gen_mulu2_i64(cpu_T0, cpu_T1, cpu_T0, cpu_regs[R_EDX]); tcg_gen_mov_i64(cpu_regs[s->vex_v], cpu_T0); tcg_gen_mov_i64(cpu_regs[reg], cpu_T1); break; #endif } break; case 0x3f5: \/* pdep Gy, By, Ey *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2) || !(s->prefix & PREFIX_VEX) || s->vex_l != 0) { goto illegal_op; } ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); \/* Note that by zero-extending the mask operand, we automatically handle zero-extending the result. *\/ if (ot == MO_64) { tcg_gen_mov_tl(cpu_T1, cpu_regs[s->vex_v]); } else { tcg_gen_ext32u_tl(cpu_T1, cpu_regs[s->vex_v]); } gen_helper_pdep(cpu_regs[reg], cpu_T0, cpu_T1); break; case 0x2f5: \/* pext Gy, By, Ey *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2) || !(s->prefix & PREFIX_VEX) || s->vex_l != 0) { goto illegal_op; } ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); \/* Note that by zero-extending the mask operand, we automatically handle zero-extending the result. *\/ if (ot == MO_64) { tcg_gen_mov_tl(cpu_T1, cpu_regs[s->vex_v]); } else { tcg_gen_ext32u_tl(cpu_T1, cpu_regs[s->vex_v]); } gen_helper_pext(cpu_regs[reg], cpu_T0, cpu_T1); break; case 0x1f6: \/* adcx Gy, Ey *\/ case 0x2f6: \/* adox Gy, Ey *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_ADX)) { goto illegal_op; } else { TCGv carry_in, carry_out, zero; int end_op; ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); \/* Re-use the carry-out from a previous round. *\/ TCGV_UNUSED(carry_in); carry_out = (b == 0x1f6 ? cpu_cc_dst : cpu_cc_src2); switch (s->cc_op) { case CC_OP_ADCX: if (b == 0x1f6) { carry_in = cpu_cc_dst; end_op = CC_OP_ADCX; } else { end_op = CC_OP_ADCOX; } break; case CC_OP_ADOX: if (b == 0x1f6) { end_op = CC_OP_ADCOX; } else { carry_in = cpu_cc_src2; end_op = CC_OP_ADOX; } break; case CC_OP_ADCOX: end_op = CC_OP_ADCOX; carry_in = carry_out; break; default: end_op = (b == 0x1f6 ? CC_OP_ADCX : CC_OP_ADOX); break; } \/* If we can't reuse carry-out, get it out of EFLAGS. *\/ if (TCGV_IS_UNUSED(carry_in)) { if (s->cc_op != CC_OP_ADCX && s->cc_op != CC_OP_ADOX) { gen_compute_eflags(s); } carry_in = cpu_tmp0; tcg_gen_extract_tl(carry_in, cpu_cc_src, ctz32(b == 0x1f6 ? CC_C : CC_O), 1); } switch (ot) { #ifdef TARGET_X86_64 case MO_32: \/* If we know TL is 64-bit, and we want a 32-bit result, just do everything in 64-bit arithmetic. *\/ tcg_gen_ext32u_i64(cpu_regs[reg], cpu_regs[reg]); tcg_gen_ext32u_i64(cpu_T0, cpu_T0); tcg_gen_add_i64(cpu_T0, cpu_T0, cpu_regs[reg]); tcg_gen_add_i64(cpu_T0, cpu_T0, carry_in); tcg_gen_ext32u_i64(cpu_regs[reg], cpu_T0); tcg_gen_shri_i64(carry_out, cpu_T0, 32); break; #endif default: \/* Otherwise compute the carry-out in two steps. *\/ zero = tcg_const_tl(0); tcg_gen_add2_tl(cpu_T0, carry_out, cpu_T0, zero, carry_in, zero); tcg_gen_add2_tl(cpu_regs[reg], carry_out, cpu_regs[reg], carry_out, cpu_T0, zero); tcg_temp_free(zero); break; } set_cc_op(s, end_op); } break; case 0x1f7: \/* shlx Gy, Ey, By *\/ case 0x2f7: \/* sarx Gy, Ey, By *\/ case 0x3f7: \/* shrx Gy, Ey, By *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2) || !(s->prefix & PREFIX_VEX) || s->vex_l != 0) { goto illegal_op; } ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); if (ot == MO_64) { tcg_gen_andi_tl(cpu_T1, cpu_regs[s->vex_v], 63); } else { tcg_gen_andi_tl(cpu_T1, cpu_regs[s->vex_v], 31); } if (b == 0x1f7) { tcg_gen_shl_tl(cpu_T0, cpu_T0, cpu_T1); } else if (b == 0x2f7) { if (ot != MO_64) { tcg_gen_ext32s_tl(cpu_T0, cpu_T0); } tcg_gen_sar_tl(cpu_T0, cpu_T0, cpu_T1); } else { if (ot != MO_64) { tcg_gen_ext32u_tl(cpu_T0, cpu_T0); } tcg_gen_shr_tl(cpu_T0, cpu_T0, cpu_T1); } gen_op_mov_reg_v(ot, reg, cpu_T0); break; case 0x0f3: case 0x1f3: case 0x2f3: case 0x3f3: \/* Group 17 *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1) || !(s->prefix & PREFIX_VEX) || s->vex_l != 0) { goto illegal_op; } ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); switch (reg & 7) { case 1: \/* blsr By,Ey *\/ tcg_gen_neg_tl(cpu_T1, cpu_T0); tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_T1); gen_op_mov_reg_v(ot, s->vex_v, cpu_T0); gen_op_update2_cc(); set_cc_op(s, CC_OP_BMILGB + ot); break; case 2: \/* blsmsk By,Ey *\/ tcg_gen_mov_tl(cpu_cc_src, cpu_T0); tcg_gen_subi_tl(cpu_T0, cpu_T0, 1); tcg_gen_xor_tl(cpu_T0, cpu_T0, cpu_cc_src); tcg_gen_mov_tl(cpu_cc_dst, cpu_T0); set_cc_op(s, CC_OP_BMILGB + ot); break; case 3: \/* blsi By, Ey *\/ tcg_gen_mov_tl(cpu_cc_src, cpu_T0); tcg_gen_subi_tl(cpu_T0, cpu_T0, 1); tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_cc_src); tcg_gen_mov_tl(cpu_cc_dst, cpu_T0); set_cc_op(s, CC_OP_BMILGB + ot); break; default: goto unknown_op; } break; default: goto unknown_op; } break; case 0x03a: case 0x13a: b = modrm; modrm = cpu_ldub_code(env, s->pc++); rm = modrm & 7; reg = ((modrm >> 3) & 7) | rex_r; mod = (modrm >> 6) & 3; if (b1 >= 2) { goto unknown_op; } sse_fn_eppi = sse_op_table7[b].op[b1]; if (!sse_fn_eppi) { goto unknown_op; } if (!(s->cpuid_ext_features & sse_op_table7[b].ext_mask)) goto illegal_op; if (sse_fn_eppi == SSE_SPECIAL) { ot = mo_64_32(s->dflag); rm = (modrm & 7) | REX_B(s); if (mod != 3) gen_lea_modrm(env, s, modrm); reg = ((modrm >> 3) & 7) | rex_r; val = cpu_ldub_code(env, s->pc++); switch (b) { case 0x14: \/* pextrb *\/ tcg_gen_ld8u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_B(val & 15))); if (mod == 3) { gen_op_mov_reg_v(ot, rm, cpu_T0); } else { tcg_gen_qemu_st_tl(cpu_T0, cpu_A0, s->mem_index, MO_UB); } break; case 0x15: \/* pextrw *\/ tcg_gen_ld16u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_W(val & 7))); if (mod == 3) { gen_op_mov_reg_v(ot, rm, cpu_T0); } else { tcg_gen_qemu_st_tl(cpu_T0, cpu_A0, s->mem_index, MO_LEUW); } break; case 0x16: if (ot == MO_32) { \/* pextrd *\/ tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_L(val & 3))); if (mod == 3) { tcg_gen_extu_i32_tl(cpu_regs[rm], cpu_tmp2_i32); } else { tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); } } else { \/* pextrq *\/ #ifdef TARGET_X86_64 tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(val & 1))); if (mod == 3) { tcg_gen_mov_i64(cpu_regs[rm], cpu_tmp1_i64); } else { tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ); } #else goto illegal_op; #endif } break; case 0x17: \/* extractps *\/ tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_L(val & 3))); if (mod == 3) { gen_op_mov_reg_v(ot, rm, cpu_T0); } else { tcg_gen_qemu_st_tl(cpu_T0, cpu_A0, s->mem_index, MO_LEUL); } break; case 0x20: \/* pinsrb *\/ if (mod == 3) { gen_op_mov_v_reg(MO_32, cpu_T0, rm); } else { tcg_gen_qemu_ld_tl(cpu_T0, cpu_A0, s->mem_index, MO_UB); } tcg_gen_st8_tl(cpu_T0, cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_B(val & 15))); break; case 0x21: \/* insertps *\/ if (mod == 3) { tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State,xmm_regs[rm] .ZMM_L((val >> 6) & 3))); } else { tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); } tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State,xmm_regs[reg] .ZMM_L((val >> 4) & 3))); if ((val >> 0) & 1) tcg_gen_st_i32(tcg_const_i32(0 \/*float32_zero*\/), cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_L(0))); if ((val >> 1) & 1) tcg_gen_st_i32(tcg_const_i32(0 \/*float32_zero*\/), cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_L(1))); if ((val >> 2) & 1) tcg_gen_st_i32(tcg_const_i32(0 \/*float32_zero*\/), cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_L(2))); if ((val >> 3) & 1) tcg_gen_st_i32(tcg_const_i32(0 \/*float32_zero*\/), cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_L(3))); break; case 0x22: if (ot == MO_32) { \/* pinsrd *\/ if (mod == 3) { tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[rm]); } else { tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL); } tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_L(val & 3))); } else { \/* pinsrq *\/ #ifdef TARGET_X86_64 if (mod == 3) { gen_op_mov_v_reg(ot, cpu_tmp1_i64, rm); } else { tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ); } tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offsetof(CPUX86State, xmm_regs[reg].ZMM_Q(val & 1))); #else goto illegal_op; #endif } break; } return; } if (b1) { op1_offset = offsetof(CPUX86State,xmm_regs[reg]); if (mod == 3) { op2_offset = offsetof(CPUX86State,xmm_regs[rm | REX_B(s)]); } else { op2_offset = offsetof(CPUX86State,xmm_t0); gen_lea_modrm(env, s, modrm); gen_ldo_env_A0(s, op2_offset); } } else { op1_offset = offsetof(CPUX86State,fpregs[reg].mmx); if (mod == 3) { op2_offset = offsetof(CPUX86State,fpregs[rm].mmx); } else { op2_offset = offsetof(CPUX86State,mmx_t0); gen_lea_modrm(env, s, modrm); gen_ldq_env_A0(s, op2_offset); } } val = cpu_ldub_code(env, s->pc++); if ((b & 0xfc) == 0x60) { \/* pcmpXstrX *\/ set_cc_op(s, CC_OP_EFLAGS); if (s->dflag == MO_64) { \/* The helper must use entire 64-bit gp registers *\/ val |= 1 << 8; } } tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset); sse_fn_eppi(cpu_env, cpu_ptr0, cpu_ptr1, tcg_const_i32(val)); break; case 0x33a: \/* Various integer extensions at 0f 3a f[0-f]. *\/ b = modrm | (b1 << 8); modrm = cpu_ldub_code(env, s->pc++); reg = ((modrm >> 3) & 7) | rex_r; switch (b) { case 0x3f0: \/* rorx Gy,Ey, Ib *\/ if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2) || !(s->prefix & PREFIX_VEX) || s->vex_l != 0) { goto illegal_op; } ot = mo_64_32(s->dflag); gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0); b = cpu_ldub_code(env, s->pc++); if (ot == MO_64) { tcg_gen_rotri_tl(cpu_T0, cpu_T0, b & 63); } else { tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0); tcg_gen_rotri_i32(cpu_tmp2_i32, cpu_tmp2_i32, b & 31); tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32); } gen_op_mov_reg_v(ot, reg, cpu_T0); break; default: goto unknown_op; } break; default: unknown_op: gen_unknown_opcode(env, s); return; } } else { \/* generic MMX or SSE operation *\/ switch(b) { case 0x70: \/* pshufx insn *\/ case 0xc6: \/* pshufx insn *\/ case 0xc2: \/* compare insns *\/ s->rip_offset = 1; break; default: break; } if (is_xmm) { op1_offset = offsetof(CPUX86State,xmm_regs[reg]); if (mod != 3) { int sz = 4; gen_lea_modrm(env, s, modrm); op2_offset = offsetof(CPUX86State,xmm_t0); switch (b) { case 0x50 ... 0x5a: case 0x5c ... 0x5f: case 0xc2: \/* Most sse scalar operations. *\/ if (b1 == 2) { sz = 2; } else if (b1 == 3) { sz = 3; } break; case 0x2e: \/* ucomis[sd] *\/ case 0x2f: \/* comis[sd] *\/ if (b1 == 0) { sz = 2; } else { sz = 3; } break; } switch (sz) { case 2: \/* 32 bit access *\/ gen_op_ld_v(s, MO_32, cpu_T0, cpu_A0); tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(0))); break; case 3: \/* 64 bit access *\/ gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_t0.ZMM_D(0))); break; default: \/* 128 bit access *\/ gen_ldo_env_A0(s, op2_offset); break; } } else { rm = (modrm & 7) | REX_B(s); op2_offset = offsetof(CPUX86State,xmm_regs[rm]); } } else { op1_offset = offsetof(CPUX86State,fpregs[reg].mmx); if (mod != 3) { gen_lea_modrm(env, s, modrm); op2_offset = offsetof(CPUX86State,mmx_t0); gen_ldq_env_A0(s, op2_offset); } else { rm = (modrm & 7); op2_offset = offsetof(CPUX86State,fpregs[rm].mmx); } } switch(b) { case 0x0f: \/* 3DNow! data insns *\/ val = cpu_ldub_code(env, s->pc++); sse_fn_epp = sse_op_table5[val]; if (!sse_fn_epp) { goto unknown_op; } if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW)) { goto illegal_op; } tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset); sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1); break; case 0x70: \/* pshufx insn *\/ case 0xc6: \/* pshufx insn *\/ val = cpu_ldub_code(env, s->pc++); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset); \/* XXX: introduce a new table? *\/ sse_fn_ppi = (SSEFunc_0_ppi)sse_fn_epp; sse_fn_ppi(cpu_ptr0, cpu_ptr1, tcg_const_i32(val)); break; case 0xc2: \/* compare insns *\/ val = cpu_ldub_code(env, s->pc++); if (val >= 8) goto unknown_op; sse_fn_epp = sse_op_table4[val][b1]; tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset); sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1); break; case 0xf7: \/* maskmov : we must prepare A0 *\/ if (mod != 3) goto illegal_op; tcg_gen_mov_tl(cpu_A0, cpu_regs[R_EDI]); gen_extu(s->aflag, cpu_A0); gen_add_A0_ds_seg(s); tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset); \/* XXX: introduce a new table? *\/ sse_fn_eppt = (SSEFunc_0_eppt)sse_fn_epp; sse_fn_eppt(cpu_env, cpu_ptr0, cpu_ptr1, cpu_A0); break; default: tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset); tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset); sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1); break; } if (b == 0x2e || b == 0x2f) { set_cc_op(s, CC_OP_EFLAGS); } } }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":160154,"input":"unicode_unfold_key(OnigCodePoint code) { static const struct ByUnfoldKey wordlist[] = { {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x1040a, 3267, 1}, {0x1e0a, 1727, 1}, {0x040a, 1016, 1}, {0x010a, 186, 1}, {0x1f0a, 2088, 1}, {0x2c0a, 2451, 1}, {0x0189, 619, 1}, {0x1f89, 134, 2}, {0x1f85, 154, 2}, {0x0389, 733, 1}, {0x03ff, 724, 1}, {0xab89, 1523, 1}, {0xab85, 1511, 1}, {0x10c89, 3384, 1}, {0x10c85, 3372, 1}, {0x1e84, 1911, 1}, {0x03f5, 752, 1}, {0x0184, 360, 1}, {0x1f84, 149, 2}, {0x2c84, 2592, 1}, {0x017d, 351, 1}, {0x1ff3, 96, 2}, {0xab84, 1508, 1}, {0xa784, 3105, 1}, {0x10c84, 3369, 1}, {0xab7d, 1487, 1}, {0xa77d, 1706, 1}, {0x1e98, 38, 2}, {0x0498, 1106, 1}, {0x0198, 375, 1}, {0x1f98, 169, 2}, {0x2c98, 2622, 1}, {0x0398, 762, 1}, {0xa684, 2940, 1}, {0xab98, 1568, 1}, {0xa798, 3123, 1}, {0x10c98, 3429, 1}, {0x050a, 1277, 1}, {0x1ffb, 2265, 1}, {0x1e96, 16, 2}, {0x0496, 1103, 1}, {0x0196, 652, 1}, {0x1f96, 199, 2}, {0x2c96, 2619, 1}, {0x0396, 756, 1}, {0xa698, 2970, 1}, {0xab96, 1562, 1}, {0xa796, 3120, 1}, {0x10c96, 3423, 1}, {0x1feb, 2259, 1}, {0x2ceb, 2736, 1}, {0x1e90, 1929, 1}, {0x0490, 1094, 1}, {0x0190, 628, 1}, {0x1f90, 169, 2}, {0x2c90, 2610, 1}, {0x0390, 25, 3}, {0xa696, 2967, 1}, {0xab90, 1544, 1}, {0xa790, 3114, 1}, {0x10c90, 3405, 1}, {0x01d7, 444, 1}, {0x1fd7, 31, 3}, {0x1ea6, 1947, 1}, {0x04a6, 1127, 1}, {0x01a6, 676, 1}, {0x1fa6, 239, 2}, {0x2ca6, 2643, 1}, {0x03a6, 810, 1}, {0xa690, 2958, 1}, {0xaba6, 1610, 1}, {0xa7a6, 3144, 1}, {0x10ca6, 3471, 1}, {0x1ea4, 1944, 1}, {0x04a4, 1124, 1}, {0x01a4, 390, 1}, {0x1fa4, 229, 2}, {0x2ca4, 2640, 1}, {0x03a4, 804, 1}, {0x10a6, 2763, 1}, {0xaba4, 1604, 1}, {0xa7a4, 3141, 1}, {0x10ca4, 3465, 1}, {0x1ea0, 1938, 1}, {0x04a0, 1118, 1}, {0x01a0, 384, 1}, {0x1fa0, 209, 2}, {0x2ca0, 2634, 1}, {0x03a0, 792, 1}, {0x10a4, 2757, 1}, {0xaba0, 1592, 1}, {0xa7a0, 3135, 1}, {0x10ca0, 3453, 1}, {0x1eb2, 1965, 1}, {0x04b2, 1145, 1}, {0x01b2, 694, 1}, {0x1fb2, 249, 2}, {0x2cb2, 2661, 1}, {0x03fd, 718, 1}, {0x10a0, 2745, 1}, {0xabb2, 1646, 1}, {0xa7b2, 703, 1}, {0x10cb2, 3507, 1}, {0x1eac, 1956, 1}, {0x04ac, 1136, 1}, {0x01ac, 396, 1}, {0x1fac, 229, 2}, {0x2cac, 2652, 1}, {0x0537, 1352, 1}, {0x10b2, 2799, 1}, {0xabac, 1628, 1}, {0xa7ac, 637, 1}, {0x10cac, 3489, 1}, {0x1eaa, 1953, 1}, {0x04aa, 1133, 1}, {0x00dd, 162, 1}, {0x1faa, 219, 2}, {0x2caa, 2649, 1}, {0x03aa, 824, 1}, {0x10ac, 2781, 1}, {0xabaa, 1622, 1}, {0xa7aa, 646, 1}, {0x10caa, 3483, 1}, {0x1ea8, 1950, 1}, {0x04a8, 1130, 1}, {0x020a, 517, 1}, {0x1fa8, 209, 2}, {0x2ca8, 2646, 1}, {0x03a8, 817, 1}, {0x10aa, 2775, 1}, {0xaba8, 1616, 1}, {0xa7a8, 3147, 1}, {0x10ca8, 3477, 1}, {0x1ea2, 1941, 1}, {0x04a2, 1121, 1}, {0x01a2, 387, 1}, {0x1fa2, 219, 2}, {0x2ca2, 2637, 1}, {0x118a6, 3528, 1}, {0x10a8, 2769, 1}, {0xaba2, 1598, 1}, {0xa7a2, 3138, 1}, {0x10ca2, 3459, 1}, {0x2ced, 2739, 1}, {0x1fe9, 2283, 1}, {0x1fe7, 47, 3}, {0x1eb0, 1962, 1}, {0x04b0, 1142, 1}, {0x118a4, 3522, 1}, {0x10a2, 2751, 1}, {0x2cb0, 2658, 1}, {0x03b0, 41, 3}, {0x1fe3, 41, 3}, {0xabb0, 1640, 1}, {0xa7b0, 706, 1}, {0x10cb0, 3501, 1}, {0x01d9, 447, 1}, {0x1fd9, 2277, 1}, {0x118a0, 3510, 1}, {0x00df, 24, 2}, {0x00d9, 150, 1}, {0xab77, 1469, 1}, {0x10b0, 2793, 1}, {0x1eae, 1959, 1}, {0x04ae, 1139, 1}, {0x01ae, 685, 1}, {0x1fae, 239, 2}, {0x2cae, 2655, 1}, {0x118b2, 3564, 1}, {0xab73, 1457, 1}, {0xabae, 1634, 1}, {0xab71, 1451, 1}, {0x10cae, 3495, 1}, {0x1e2a, 1775, 1}, {0x042a, 968, 1}, {0x012a, 234, 1}, {0x1f2a, 2130, 1}, {0x2c2a, 2547, 1}, {0x118ac, 3546, 1}, {0x10ae, 2787, 1}, {0x0535, 1346, 1}, {0xa72a, 2988, 1}, {0x1e9a, 0, 2}, {0x049a, 1109, 1}, {0xff37, 3225, 1}, {0x1f9a, 179, 2}, {0x2c9a, 2625, 1}, {0x039a, 772, 1}, {0x118aa, 3540, 1}, {0xab9a, 1574, 1}, {0xa79a, 3126, 1}, {0x10c9a, 3435, 1}, {0x1e94, 1935, 1}, {0x0494, 1100, 1}, {0x0194, 640, 1}, {0x1f94, 189, 2}, {0x2c94, 2616, 1}, {0x0394, 749, 1}, {0x118a8, 3534, 1}, {0xab94, 1556, 1}, {0xa69a, 2973, 1}, {0x10c94, 3417, 1}, {0x10402, 3243, 1}, {0x1e02, 1715, 1}, {0x0402, 992, 1}, {0x0102, 174, 1}, {0x0533, 1340, 1}, {0x2c02, 2427, 1}, {0x118a2, 3516, 1}, {0x052a, 1325, 1}, {0xa694, 2964, 1}, {0x1e92, 1932, 1}, {0x0492, 1097, 1}, {0x2165, 2307, 1}, {0x1f92, 179, 2}, {0x2c92, 2613, 1}, {0x0392, 742, 1}, {0x2161, 2295, 1}, {0xab92, 1550, 1}, {0xa792, 3117, 1}, {0x10c92, 3411, 1}, {0x118b0, 3558, 1}, {0x1f5f, 2199, 1}, {0x1e8e, 1926, 1}, {0x048e, 1091, 1}, {0x018e, 453, 1}, {0x1f8e, 159, 2}, {0x2c8e, 2607, 1}, {0x038e, 833, 1}, {0xa692, 2961, 1}, {0xab8e, 1538, 1}, {0x0055, 59, 1}, {0x10c8e, 3399, 1}, {0x1f5d, 2196, 1}, {0x212a, 27, 1}, {0x04cb, 1181, 1}, {0x01cb, 425, 1}, {0x1fcb, 2241, 1}, {0x118ae, 3552, 1}, {0x0502, 1265, 1}, {0x00cb, 111, 1}, {0xa68e, 2955, 1}, {0x1e8a, 1920, 1}, {0x048a, 1085, 1}, {0x018a, 622, 1}, {0x1f8a, 139, 2}, {0x2c8a, 2601, 1}, {0x038a, 736, 1}, {0x2c67, 2571, 1}, {0xab8a, 1526, 1}, {0x1e86, 1914, 1}, {0x10c8a, 3387, 1}, {0x0186, 616, 1}, {0x1f86, 159, 2}, {0x2c86, 2595, 1}, {0x0386, 727, 1}, {0xff35, 3219, 1}, {0xab86, 1514, 1}, {0xa786, 3108, 1}, {0x10c86, 3375, 1}, {0xa68a, 2949, 1}, {0x0555, 1442, 1}, {0x1ebc, 1980, 1}, {0x04bc, 1160, 1}, {0x01bc, 411, 1}, {0x1fbc, 62, 2}, {0x2cbc, 2676, 1}, {0x1f5b, 2193, 1}, {0xa686, 2943, 1}, {0xabbc, 1676, 1}, {0x1eb8, 1974, 1}, {0x04b8, 1154, 1}, {0x01b8, 408, 1}, {0x1fb8, 2268, 1}, {0x2cb8, 2670, 1}, {0x01db, 450, 1}, {0x1fdb, 2247, 1}, {0xabb8, 1664, 1}, {0x10bc, 2829, 1}, {0x00db, 156, 1}, {0x1eb6, 1971, 1}, {0x04b6, 1151, 1}, {0xff33, 3213, 1}, {0x1fb6, 58, 2}, {0x2cb6, 2667, 1}, {0xff2a, 3186, 1}, {0x10b8, 2817, 1}, {0xabb6, 1658, 1}, {0xa7b6, 3153, 1}, {0x10426, 3351, 1}, {0x1e26, 1769, 1}, {0x0426, 956, 1}, {0x0126, 228, 1}, {0x0053, 52, 1}, {0x2c26, 2535, 1}, {0x0057, 65, 1}, {0x10b6, 2811, 1}, {0x022a, 562, 1}, {0xa726, 2982, 1}, {0x1e2e, 1781, 1}, {0x042e, 980, 1}, {0x012e, 240, 1}, {0x1f2e, 2142, 1}, {0x2c2e, 2559, 1}, {0xffffffff, -1, 0}, {0x2167, 2313, 1}, {0xffffffff, -1, 0}, {0xa72e, 2994, 1}, {0x1e2c, 1778, 1}, {0x042c, 974, 1}, {0x012c, 237, 1}, {0x1f2c, 2136, 1}, {0x2c2c, 2553, 1}, {0x1f6f, 2223, 1}, {0x2c6f, 604, 1}, {0xabbf, 1685, 1}, {0xa72c, 2991, 1}, {0x1e28, 1772, 1}, {0x0428, 962, 1}, {0x0128, 231, 1}, {0x1f28, 2124, 1}, {0x2c28, 2541, 1}, {0xffffffff, -1, 0}, {0x0553, 1436, 1}, {0x10bf, 2838, 1}, {0xa728, 2985, 1}, {0x0526, 1319, 1}, {0x0202, 505, 1}, {0x1e40, 1808, 1}, {0x10424, 3345, 1}, {0x1e24, 1766, 1}, {0x0424, 950, 1}, {0x0124, 225, 1}, {0xffffffff, -1, 0}, {0x2c24, 2529, 1}, {0x052e, 1331, 1}, {0xa740, 3018, 1}, {0x118bc, 3594, 1}, {0xa724, 2979, 1}, {0x1ef2, 2061, 1}, {0x04f2, 1241, 1}, {0x01f2, 483, 1}, {0x1ff2, 257, 2}, {0x2cf2, 2742, 1}, {0x052c, 1328, 1}, {0x118b8, 3582, 1}, {0xa640, 2865, 1}, {0x10422, 3339, 1}, {0x1e22, 1763, 1}, {0x0422, 944, 1}, {0x0122, 222, 1}, {0x2126, 820, 1}, {0x2c22, 2523, 1}, {0x0528, 1322, 1}, {0x01f1, 483, 1}, {0x118b6, 3576, 1}, {0xa722, 2976, 1}, {0x03f1, 796, 1}, {0x1ebe, 1983, 1}, {0x04be, 1163, 1}, {0xfb02, 12, 2}, {0x1fbe, 767, 1}, {0x2cbe, 2679, 1}, {0x01b5, 405, 1}, {0x0540, 1379, 1}, {0xabbe, 1682, 1}, {0x0524, 1316, 1}, {0x00b5, 779, 1}, {0xabb5, 1655, 1}, {0x1eba, 1977, 1}, {0x04ba, 1157, 1}, {0x216f, 2337, 1}, {0x1fba, 2226, 1}, {0x2cba, 2673, 1}, {0x10be, 2835, 1}, {0x0051, 46, 1}, {0xabba, 1670, 1}, {0x10b5, 2808, 1}, {0x1e6e, 1878, 1}, {0x046e, 1055, 1}, {0x016e, 330, 1}, {0x1f6e, 2220, 1}, {0x2c6e, 664, 1}, {0x118bf, 3603, 1}, {0x0522, 1313, 1}, {0x10ba, 2823, 1}, {0xa76e, 3087, 1}, {0x1eb4, 1968, 1}, {0x04b4, 1148, 1}, {0x2c75, 2583, 1}, {0x1fb4, 50, 2}, {0x2cb4, 2664, 1}, {0xab75, 1463, 1}, {0x1ec2, 1989, 1}, {0xabb4, 1652, 1}, {0xa7b4, 3150, 1}, {0x1fc2, 253, 2}, {0x2cc2, 2685, 1}, {0x03c2, 800, 1}, {0x00c2, 83, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff26, 3174, 1}, {0x10b4, 2805, 1}, {0x1eca, 2001, 1}, {0x0551, 1430, 1}, {0x01ca, 425, 1}, {0x1fca, 2238, 1}, {0x2cca, 2697, 1}, {0x10c2, 2847, 1}, {0x00ca, 108, 1}, {0xff2e, 3198, 1}, {0x1e8c, 1923, 1}, {0x048c, 1088, 1}, {0x0226, 556, 1}, {0x1f8c, 149, 2}, {0x2c8c, 2604, 1}, {0x038c, 830, 1}, {0xffffffff, -1, 0}, {0xab8c, 1532, 1}, {0xff2c, 3192, 1}, {0x10c8c, 3393, 1}, {0x1ec4, 1992, 1}, {0x022e, 568, 1}, {0x01c4, 417, 1}, {0x1fc4, 54, 2}, {0x2cc4, 2688, 1}, {0xffffffff, -1, 0}, {0x00c4, 89, 1}, {0xff28, 3180, 1}, {0xa68c, 2952, 1}, {0x01cf, 432, 1}, {0x022c, 565, 1}, {0x118be, 3600, 1}, {0x03cf, 839, 1}, {0x00cf, 123, 1}, {0x118b5, 3573, 1}, {0xffffffff, -1, 0}, {0x10c4, 2853, 1}, {0x216e, 2334, 1}, {0x24cb, 2406, 1}, {0x0228, 559, 1}, {0xff24, 3168, 1}, {0xffffffff, -1, 0}, {0x118ba, 3588, 1}, {0x1efe, 2079, 1}, {0x04fe, 1259, 1}, {0x01fe, 499, 1}, {0x1e9e, 24, 2}, {0x049e, 1115, 1}, {0x03fe, 721, 1}, {0x1f9e, 199, 2}, {0x2c9e, 2631, 1}, {0x039e, 786, 1}, {0x0224, 553, 1}, {0xab9e, 1586, 1}, {0xa79e, 3132, 1}, {0x10c9e, 3447, 1}, {0x01f7, 414, 1}, {0x1ff7, 67, 3}, {0xff22, 3162, 1}, {0x03f7, 884, 1}, {0x118b4, 3570, 1}, {0x049c, 1112, 1}, {0x019c, 661, 1}, {0x1f9c, 189, 2}, {0x2c9c, 2628, 1}, {0x039c, 779, 1}, {0x24bc, 2361, 1}, {0xab9c, 1580, 1}, {0xa79c, 3129, 1}, {0x10c9c, 3441, 1}, {0x0222, 550, 1}, {0x1e7c, 1899, 1}, {0x047c, 1076, 1}, {0x1e82, 1908, 1}, {0x24b8, 2349, 1}, {0x0182, 357, 1}, {0x1f82, 139, 2}, {0x2c82, 2589, 1}, {0xab7c, 1484, 1}, {0xffffffff, -1, 0}, {0xab82, 1502, 1}, {0xa782, 3102, 1}, {0x10c82, 3363, 1}, {0x2c63, 1709, 1}, {0x24b6, 2343, 1}, {0x1e80, 1905, 1}, {0x0480, 1082, 1}, {0x1f59, 2190, 1}, {0x1f80, 129, 2}, {0x2c80, 2586, 1}, {0x0059, 71, 1}, {0xa682, 2937, 1}, {0xab80, 1496, 1}, {0xa780, 3099, 1}, {0x10c80, 3357, 1}, {0xffffffff, -1, 0}, {0x1e4c, 1826, 1}, {0x0145, 270, 1}, {0x014c, 279, 1}, {0x1f4c, 2184, 1}, {0x0345, 767, 1}, {0x0045, 12, 1}, {0x004c, 31, 1}, {0xa680, 2934, 1}, {0xa74c, 3036, 1}, {0x1e4a, 1823, 1}, {0x01d5, 441, 1}, {0x014a, 276, 1}, {0x1f4a, 2178, 1}, {0x03d5, 810, 1}, {0x00d5, 141, 1}, {0x004a, 24, 1}, {0x24bf, 2370, 1}, {0xa74a, 3033, 1}, {0xa64c, 2883, 1}, {0x1041c, 3321, 1}, {0x1e1c, 1754, 1}, {0x041c, 926, 1}, {0x011c, 213, 1}, {0x1f1c, 2118, 1}, {0x2c1c, 2505, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xa64a, 2880, 1}, {0x1041a, 3315, 1}, {0x1e1a, 1751, 1}, {0x041a, 920, 1}, {0x011a, 210, 1}, {0x1f1a, 2112, 1}, {0x2c1a, 2499, 1}, {0xabbd, 1679, 1}, {0x0545, 1394, 1}, {0x054c, 1415, 1}, {0x10418, 3309, 1}, {0x1e18, 1748, 1}, {0x0418, 914, 1}, {0x0118, 207, 1}, {0x1f18, 2106, 1}, {0x2c18, 2493, 1}, {0x10bd, 2832, 1}, {0x2163, 2301, 1}, {0x054a, 1409, 1}, {0x1040e, 3279, 1}, {0x1e0e, 1733, 1}, {0x040e, 1028, 1}, {0x010e, 192, 1}, {0x1f0e, 2100, 1}, {0x2c0e, 2463, 1}, {0x1efc, 2076, 1}, {0x04fc, 1256, 1}, {0x01fc, 496, 1}, {0x1ffc, 96, 2}, {0x051c, 1304, 1}, {0x1040c, 3273, 1}, {0x1e0c, 1730, 1}, {0x040c, 1022, 1}, {0x010c, 189, 1}, {0x1f0c, 2094, 1}, {0x2c0c, 2457, 1}, {0x1f6d, 2217, 1}, {0x2c6d, 607, 1}, {0x051a, 1301, 1}, {0x24be, 2367, 1}, {0x10408, 3261, 1}, {0x1e08, 1724, 1}, {0x0408, 1010, 1}, {0x0108, 183, 1}, {0x1f08, 2082, 1}, {0x2c08, 2445, 1}, {0x04c9, 1178, 1}, {0x0518, 1298, 1}, {0x1fc9, 2235, 1}, {0xffffffff, -1, 0}, {0x24ba, 2355, 1}, {0x00c9, 105, 1}, {0x10416, 3303, 1}, {0x1e16, 1745, 1}, {0x0416, 908, 1}, {0x0116, 204, 1}, {0x050e, 1283, 1}, {0x2c16, 2487, 1}, {0x10414, 3297, 1}, {0x1e14, 1742, 1}, {0x0414, 902, 1}, {0x0114, 201, 1}, {0x042b, 971, 1}, {0x2c14, 2481, 1}, {0x1f2b, 2133, 1}, {0x2c2b, 2550, 1}, {0xffffffff, -1, 0}, {0x050c, 1280, 1}, {0x10406, 3255, 1}, {0x1e06, 1721, 1}, {0x0406, 1004, 1}, {0x0106, 180, 1}, {0x13fb, 1697, 1}, {0x2c06, 2439, 1}, {0x24c2, 2379, 1}, {0x118bd, 3597, 1}, {0xffffffff, -1, 0}, {0x0508, 1274, 1}, {0x10404, 3249, 1}, {0x1e04, 1718, 1}, {0x0404, 998, 1}, {0x0104, 177, 1}, {0x1f95, 194, 2}, {0x2c04, 2433, 1}, {0x0395, 752, 1}, {0x24ca, 2403, 1}, {0xab95, 1559, 1}, {0x0531, 1334, 1}, {0x10c95, 3420, 1}, {0x0516, 1295, 1}, {0x1e6c, 1875, 1}, {0x046c, 1052, 1}, {0x016c, 327, 1}, {0x1f6c, 2214, 1}, {0x216d, 2331, 1}, {0x0514, 1292, 1}, {0x0245, 697, 1}, {0x024c, 598, 1}, {0xa76c, 3084, 1}, {0x10400, 3237, 1}, {0x1e00, 1712, 1}, {0x0400, 986, 1}, {0x0100, 171, 1}, {0x24c4, 2385, 1}, {0x2c00, 2421, 1}, {0x0506, 1271, 1}, {0x024a, 595, 1}, {0x1fab, 224, 2}, {0xa66c, 2931, 1}, {0x03ab, 827, 1}, {0x24cf, 2418, 1}, {0xabab, 1625, 1}, {0xa7ab, 631, 1}, {0x10cab, 3486, 1}, {0xffffffff, -1, 0}, {0x0504, 1268, 1}, {0xffffffff, -1, 0}, {0x021c, 544, 1}, {0x01a9, 679, 1}, {0x1fa9, 214, 2}, {0x10ab, 2778, 1}, {0x03a9, 820, 1}, {0x212b, 92, 1}, {0xaba9, 1619, 1}, {0x1e88, 1917, 1}, {0x10ca9, 3480, 1}, {0x021a, 541, 1}, {0x1f88, 129, 2}, {0x2c88, 2598, 1}, {0x0388, 730, 1}, {0x13fd, 1703, 1}, {0xab88, 1520, 1}, {0x10a9, 2772, 1}, {0x10c88, 3381, 1}, {0xffffffff, -1, 0}, {0x0218, 538, 1}, {0x0500, 1262, 1}, {0x1f4d, 2187, 1}, {0x01a7, 393, 1}, {0x1fa7, 244, 2}, {0x004d, 34, 1}, {0x03a7, 814, 1}, {0xa688, 2946, 1}, {0xaba7, 1613, 1}, {0x020e, 523, 1}, {0x10ca7, 3474, 1}, {0x1e6a, 1872, 1}, {0x046a, 1049, 1}, {0x016a, 324, 1}, {0x1f6a, 2208, 1}, {0xffffffff, -1, 0}, {0x216c, 2328, 1}, {0x10a7, 2766, 1}, {0x01d1, 435, 1}, {0xa76a, 3081, 1}, {0x020c, 520, 1}, {0x03d1, 762, 1}, {0x00d1, 129, 1}, {0x1e68, 1869, 1}, {0x0468, 1046, 1}, {0x0168, 321, 1}, {0x1f68, 2202, 1}, {0xffffffff, -1, 0}, {0xff31, 3207, 1}, {0xa66a, 2928, 1}, {0x0208, 514, 1}, {0xa768, 3078, 1}, {0x1e64, 1863, 1}, {0x0464, 1040, 1}, {0x0164, 315, 1}, {0x054d, 1418, 1}, {0x2c64, 673, 1}, {0xffffffff, -1, 0}, {0xff2b, 3189, 1}, {0xffffffff, -1, 0}, {0xa764, 3072, 1}, {0xa668, 2925, 1}, {0x0216, 535, 1}, {0xffffffff, -1, 0}, {0x118ab, 3543, 1}, {0x1e62, 1860, 1}, {0x0462, 1037, 1}, {0x0162, 312, 1}, {0x0214, 532, 1}, {0x2c62, 655, 1}, {0xa664, 2919, 1}, {0x1ed2, 2013, 1}, {0x04d2, 1193, 1}, {0xa762, 3069, 1}, {0x1fd2, 20, 3}, {0x2cd2, 2709, 1}, {0x118a9, 3537, 1}, {0x00d2, 132, 1}, {0x0206, 511, 1}, {0x10420, 3333, 1}, {0x1e20, 1760, 1}, {0x0420, 938, 1}, {0x0120, 219, 1}, {0xa662, 2916, 1}, {0x2c20, 2517, 1}, {0x1e60, 1856, 1}, {0x0460, 1034, 1}, {0x0160, 309, 1}, {0x0204, 508, 1}, {0x2c60, 2562, 1}, {0xffffffff, -1, 0}, {0x24bd, 2364, 1}, {0x216a, 2322, 1}, {0xa760, 3066, 1}, {0xffffffff, -1, 0}, {0xfb16, 125, 2}, {0x118a7, 3531, 1}, {0x1efa, 2073, 1}, {0x04fa, 1253, 1}, {0x01fa, 493, 1}, {0x1ffa, 2262, 1}, {0xfb14, 109, 2}, {0x03fa, 887, 1}, {0xa660, 2913, 1}, {0x2168, 2316, 1}, {0x01b7, 700, 1}, {0x1fb7, 10, 3}, {0x1f6b, 2211, 1}, {0x2c6b, 2577, 1}, {0x0200, 502, 1}, {0xabb7, 1661, 1}, {0xfb06, 29, 2}, {0x1e56, 1841, 1}, {0x2164, 2304, 1}, {0x0156, 294, 1}, {0x1f56, 62, 3}, {0x0520, 1310, 1}, {0x004f, 40, 1}, {0x0056, 62, 1}, {0x10b7, 2814, 1}, {0xa756, 3051, 1}, {0xfb04, 5, 3}, {0x1e78, 1893, 1}, {0x0478, 1070, 1}, {0x0178, 168, 1}, {0x1e54, 1838, 1}, {0x2162, 2298, 1}, {0x0154, 291, 1}, {0x1f54, 57, 3}, {0xab78, 1472, 1}, {0xa656, 2898, 1}, {0x0054, 56, 1}, {0x1e52, 1835, 1}, {0xa754, 3048, 1}, {0x0152, 288, 1}, {0x1f52, 52, 3}, {0x24c9, 2400, 1}, {0x1e32, 1787, 1}, {0x0052, 49, 1}, {0x0132, 243, 1}, {0xa752, 3045, 1}, {0xffffffff, -1, 0}, {0xfb00, 4, 2}, {0xa654, 2895, 1}, {0xffffffff, -1, 0}, {0xa732, 2997, 1}, {0x2160, 2292, 1}, {0x054f, 1424, 1}, {0x0556, 1445, 1}, {0x1e50, 1832, 1}, {0xa652, 2892, 1}, {0x0150, 285, 1}, {0x1f50, 84, 2}, {0x017b, 348, 1}, {0x1e4e, 1829, 1}, {0x0050, 43, 1}, {0x014e, 282, 1}, {0xa750, 3042, 1}, {0xab7b, 1481, 1}, {0xa77b, 3093, 1}, {0x004e, 37, 1}, {0x0554, 1439, 1}, {0xa74e, 3039, 1}, {0x1e48, 1820, 1}, {0xffffffff, -1, 0}, {0x216b, 2325, 1}, {0x1f48, 2172, 1}, {0xa650, 2889, 1}, {0x0552, 1433, 1}, {0x0048, 21, 1}, {0xffffffff, -1, 0}, {0xa748, 3030, 1}, {0xa64e, 2886, 1}, {0x0532, 1337, 1}, {0x1041e, 3327, 1}, {0x1e1e, 1757, 1}, {0x041e, 932, 1}, {0x011e, 216, 1}, {0x118b7, 3579, 1}, {0x2c1e, 2511, 1}, {0xffffffff, -1, 0}, {0xa648, 2877, 1}, {0x1ff9, 2253, 1}, {0xffffffff, -1, 0}, {0x03f9, 878, 1}, {0x0550, 1427, 1}, {0x10412, 3291, 1}, {0x1e12, 1739, 1}, {0x0412, 896, 1}, {0x0112, 198, 1}, {0x054e, 1421, 1}, {0x2c12, 2475, 1}, {0x10410, 3285, 1}, {0x1e10, 1736, 1}, {0x0410, 890, 1}, {0x0110, 195, 1}, {0xffffffff, -1, 0}, {0x2c10, 2469, 1}, {0x2132, 2289, 1}, {0x0548, 1403, 1}, {0x1ef8, 2070, 1}, {0x04f8, 1250, 1}, {0x01f8, 490, 1}, {0x1ff8, 2250, 1}, {0x0220, 381, 1}, {0x1ee2, 2037, 1}, {0x04e2, 1217, 1}, {0x01e2, 462, 1}, {0x1fe2, 36, 3}, {0x2ce2, 2733, 1}, {0x03e2, 857, 1}, {0x051e, 1307, 1}, {0x1ede, 2031, 1}, {0x04de, 1211, 1}, {0x01de, 456, 1}, {0xffffffff, -1, 0}, {0x2cde, 2727, 1}, {0x03de, 851, 1}, {0x00de, 165, 1}, {0x1f69, 2205, 1}, {0x2c69, 2574, 1}, {0x1eda, 2025, 1}, {0x04da, 1205, 1}, {0x0512, 1289, 1}, {0x1fda, 2244, 1}, {0x2cda, 2721, 1}, {0x03da, 845, 1}, {0x00da, 153, 1}, {0xffffffff, -1, 0}, {0x0510, 1286, 1}, {0x1ed8, 2022, 1}, {0x04d8, 1202, 1}, {0xffffffff, -1, 0}, {0x1fd8, 2274, 1}, {0x2cd8, 2718, 1}, {0x03d8, 842, 1}, {0x00d8, 147, 1}, {0x1ed6, 2019, 1}, {0x04d6, 1199, 1}, {0xffffffff, -1, 0}, {0x1fd6, 76, 2}, {0x2cd6, 2715, 1}, {0x03d6, 792, 1}, {0x00d6, 144, 1}, {0x1ec8, 1998, 1}, {0xffffffff, -1, 0}, {0x01c8, 421, 1}, {0x1fc8, 2232, 1}, {0x2cc8, 2694, 1}, {0xff32, 3210, 1}, {0x00c8, 102, 1}, {0x04c7, 1175, 1}, {0x01c7, 421, 1}, {0x1fc7, 15, 3}, {0x1ec0, 1986, 1}, {0x04c0, 1187, 1}, {0x00c7, 99, 1}, {0xffffffff, -1, 0}, {0x2cc0, 2682, 1}, {0x0179, 345, 1}, {0x00c0, 77, 1}, {0x0232, 574, 1}, {0x01b3, 402, 1}, {0x1fb3, 62, 2}, {0xab79, 1475, 1}, {0xa779, 3090, 1}, {0x10c7, 2859, 1}, {0xabb3, 1649, 1}, {0xa7b3, 3156, 1}, {0x1fa5, 234, 2}, {0x10c0, 2841, 1}, {0x03a5, 807, 1}, {0xffffffff, -1, 0}, {0xaba5, 1607, 1}, {0x01b1, 691, 1}, {0x10ca5, 3468, 1}, {0x10b3, 2802, 1}, {0x2169, 2319, 1}, {0x024e, 601, 1}, {0xabb1, 1643, 1}, {0xa7b1, 682, 1}, {0x10cb1, 3504, 1}, {0x10a5, 2760, 1}, {0xffffffff, -1, 0}, {0x01af, 399, 1}, {0x1faf, 244, 2}, {0xffffffff, -1, 0}, {0x0248, 592, 1}, {0x10b1, 2796, 1}, {0xabaf, 1637, 1}, {0x1fad, 234, 2}, {0x10caf, 3498, 1}, {0x04cd, 1184, 1}, {0x01cd, 429, 1}, {0xabad, 1631, 1}, {0xa7ad, 658, 1}, {0x10cad, 3492, 1}, {0x00cd, 117, 1}, {0x10af, 2790, 1}, {0x021e, 547, 1}, {0x1fa3, 224, 2}, {0xffffffff, -1, 0}, {0x03a3, 800, 1}, {0x10ad, 2784, 1}, {0xaba3, 1601, 1}, {0xffffffff, -1, 0}, {0x10ca3, 3462, 1}, {0x10cd, 2862, 1}, {0x1fa1, 214, 2}, {0x24b7, 2346, 1}, {0x03a1, 796, 1}, {0x0212, 529, 1}, {0xaba1, 1595, 1}, {0x10a3, 2754, 1}, {0x10ca1, 3456, 1}, {0x01d3, 438, 1}, {0x1fd3, 25, 3}, {0x0210, 526, 1}, {0xffffffff, -1, 0}, {0x00d3, 135, 1}, {0x1e97, 34, 2}, {0x10a1, 2748, 1}, {0x0197, 649, 1}, {0x1f97, 204, 2}, {0xffffffff, -1, 0}, {0x0397, 759, 1}, {0x1041d, 3324, 1}, {0xab97, 1565, 1}, {0x041d, 929, 1}, {0x10c97, 3426, 1}, {0x1f1d, 2121, 1}, {0x2c1d, 2508, 1}, {0x1e72, 1884, 1}, {0x0472, 1061, 1}, {0x0172, 336, 1}, {0x118b3, 3567, 1}, {0x2c72, 2580, 1}, {0x0372, 712, 1}, {0x1041b, 3318, 1}, {0xab72, 1454, 1}, {0x041b, 923, 1}, {0x118a5, 3525, 1}, {0x1f1b, 2115, 1}, {0x2c1b, 2502, 1}, {0x1e70, 1881, 1}, {0x0470, 1058, 1}, {0x0170, 333, 1}, {0x118b1, 3561, 1}, {0x2c70, 610, 1}, {0x0370, 709, 1}, {0x1e46, 1817, 1}, {0xab70, 1448, 1}, {0x1e66, 1866, 1}, {0x0466, 1043, 1}, {0x0166, 318, 1}, {0x1e44, 1814, 1}, {0x0046, 15, 1}, {0x118af, 3555, 1}, {0xa746, 3027, 1}, {0xffffffff, -1, 0}, {0xa766, 3075, 1}, {0x0044, 9, 1}, {0x118ad, 3549, 1}, {0xa744, 3024, 1}, {0x1e7a, 1896, 1}, {0x047a, 1073, 1}, {0x1e3a, 1799, 1}, {0xffffffff, -1, 0}, {0xa646, 2874, 1}, {0x1f3a, 2154, 1}, {0xa666, 2922, 1}, {0xab7a, 1478, 1}, {0x118a3, 3519, 1}, {0xa644, 2871, 1}, {0xa73a, 3009, 1}, {0xffffffff, -1, 0}, {0x1ef4, 2064, 1}, {0x04f4, 1244, 1}, {0x01f4, 487, 1}, {0x1ff4, 101, 2}, {0x118a1, 3513, 1}, {0x03f4, 762, 1}, {0x1eec, 2052, 1}, {0x04ec, 1232, 1}, {0x01ec, 477, 1}, {0x1fec, 2286, 1}, {0x0546, 1397, 1}, {0x03ec, 872, 1}, {0xffffffff, -1, 0}, {0x013f, 261, 1}, {0x1f3f, 2169, 1}, {0x0544, 1391, 1}, {0x1eea, 2049, 1}, {0x04ea, 1229, 1}, {0x01ea, 474, 1}, {0x1fea, 2256, 1}, {0xffffffff, -1, 0}, {0x03ea, 869, 1}, {0x1ee8, 2046, 1}, {0x04e8, 1226, 1}, {0x01e8, 471, 1}, {0x1fe8, 2280, 1}, {0x053a, 1361, 1}, {0x03e8, 866, 1}, {0x1ee6, 2043, 1}, {0x04e6, 1223, 1}, {0x01e6, 468, 1}, {0x1fe6, 88, 2}, {0x1f4b, 2181, 1}, {0x03e6, 863, 1}, {0x1e5e, 1853, 1}, {0x004b, 27, 1}, {0x015e, 306, 1}, {0x2166, 2310, 1}, {0x1ee4, 2040, 1}, {0x04e4, 1220, 1}, {0x01e4, 465, 1}, {0x1fe4, 80, 2}, {0xa75e, 3063, 1}, {0x03e4, 860, 1}, {0x1ee0, 2034, 1}, {0x04e0, 1214, 1}, {0x01e0, 459, 1}, {0x053f, 1376, 1}, {0x2ce0, 2730, 1}, {0x03e0, 854, 1}, {0x1edc, 2028, 1}, {0x04dc, 1208, 1}, {0xa65e, 2910, 1}, {0xffffffff, -1, 0}, {0x2cdc, 2724, 1}, {0x03dc, 848, 1}, {0x00dc, 159, 1}, {0x1ed0, 2010, 1}, {0x04d0, 1190, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x2cd0, 2706, 1}, {0x03d0, 742, 1}, {0x00d0, 126, 1}, {0x1ecc, 2004, 1}, {0x054b, 1412, 1}, {0xffffffff, -1, 0}, {0x1fcc, 71, 2}, {0x2ccc, 2700, 1}, {0x1ec6, 1995, 1}, {0x00cc, 114, 1}, {0xffffffff, -1, 0}, {0x1fc6, 67, 2}, {0x2cc6, 2691, 1}, {0x24c8, 2397, 1}, {0x00c6, 96, 1}, {0x04c5, 1172, 1}, {0x01c5, 417, 1}, {0xffffffff, -1, 0}, {0x1fbb, 2229, 1}, {0x24c7, 2394, 1}, {0x00c5, 92, 1}, {0x1fb9, 2271, 1}, {0xabbb, 1673, 1}, {0x24c0, 2373, 1}, {0x04c3, 1169, 1}, {0xabb9, 1667, 1}, {0x1fc3, 71, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x00c3, 86, 1}, {0x10c5, 2856, 1}, {0x10bb, 2826, 1}, {0x1ed4, 2016, 1}, {0x04d4, 1196, 1}, {0x10b9, 2820, 1}, {0x13fc, 1700, 1}, {0x2cd4, 2712, 1}, {0x0246, 589, 1}, {0x00d4, 138, 1}, {0x10c3, 2850, 1}, {0xffffffff, -1, 0}, {0xff3a, 3234, 1}, {0x0244, 688, 1}, {0x019f, 670, 1}, {0x1f9f, 204, 2}, {0xffffffff, -1, 0}, {0x039f, 789, 1}, {0xffffffff, -1, 0}, {0xab9f, 1589, 1}, {0xffffffff, -1, 0}, {0x10c9f, 3450, 1}, {0x019d, 667, 1}, {0x1f9d, 194, 2}, {0x023a, 2565, 1}, {0x039d, 783, 1}, {0x1e5a, 1847, 1}, {0xab9d, 1583, 1}, {0x015a, 300, 1}, {0x10c9d, 3444, 1}, {0x1e9b, 1856, 1}, {0x24cd, 2412, 1}, {0x005a, 74, 1}, {0x1f9b, 184, 2}, {0xa75a, 3057, 1}, {0x039b, 776, 1}, {0x1ece, 2007, 1}, {0xab9b, 1577, 1}, {0x1e99, 42, 2}, {0x10c9b, 3438, 1}, {0x2cce, 2703, 1}, {0x1f99, 174, 2}, {0x00ce, 120, 1}, {0x0399, 767, 1}, {0xa65a, 2904, 1}, {0xab99, 1571, 1}, {0xffffffff, -1, 0}, {0x10c99, 3432, 1}, {0x0193, 634, 1}, {0x1f93, 184, 2}, {0x1e58, 1844, 1}, {0x0393, 746, 1}, {0x0158, 297, 1}, {0xab93, 1553, 1}, {0xffffffff, -1, 0}, {0x10c93, 3414, 1}, {0x0058, 68, 1}, {0x042d, 977, 1}, {0xa758, 3054, 1}, {0x1f2d, 2139, 1}, {0x2c2d, 2556, 1}, {0x118bb, 3591, 1}, {0x0191, 369, 1}, {0x1f91, 174, 2}, {0x118b9, 3585, 1}, {0x0391, 739, 1}, {0xffffffff, -1, 0}, {0xab91, 1547, 1}, {0xa658, 2901, 1}, {0x10c91, 3408, 1}, {0x018f, 625, 1}, {0x1f8f, 164, 2}, {0xffffffff, -1, 0}, {0x038f, 836, 1}, {0xffffffff, -1, 0}, {0xab8f, 1541, 1}, {0xffffffff, -1, 0}, {0x10c8f, 3402, 1}, {0x018b, 366, 1}, {0x1f8b, 144, 2}, {0xffffffff, -1, 0}, {0x0187, 363, 1}, {0x1f87, 164, 2}, {0xab8b, 1529, 1}, {0xa78b, 3111, 1}, {0x10c8b, 3390, 1}, {0xab87, 1517, 1}, {0x04c1, 1166, 1}, {0x10c87, 3378, 1}, {0x1e7e, 1902, 1}, {0x047e, 1079, 1}, {0xffffffff, -1, 0}, {0x00c1, 80, 1}, {0x2c7e, 580, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab7e, 1490, 1}, {0xa77e, 3096, 1}, {0x1e76, 1890, 1}, {0x0476, 1067, 1}, {0x0176, 342, 1}, {0x1e42, 1811, 1}, {0x10c1, 2844, 1}, {0x0376, 715, 1}, {0x1e36, 1793, 1}, {0xab76, 1466, 1}, {0x0136, 249, 1}, {0x0042, 3, 1}, {0x1e3e, 1805, 1}, {0xa742, 3021, 1}, {0x1e38, 1796, 1}, {0x1f3e, 2166, 1}, {0xa736, 3003, 1}, {0x1f38, 2148, 1}, {0xffffffff, -1, 0}, {0x0587, 105, 2}, {0xa73e, 3015, 1}, {0xffffffff, -1, 0}, {0xa738, 3006, 1}, {0xa642, 2868, 1}, {0x1e5c, 1850, 1}, {0x1e34, 1790, 1}, {0x015c, 303, 1}, {0x0134, 246, 1}, {0x1ef6, 2067, 1}, {0x04f6, 1247, 1}, {0x01f6, 372, 1}, {0x1ff6, 92, 2}, {0xa75c, 3060, 1}, {0xa734, 3000, 1}, {0x1ef0, 2058, 1}, {0x04f0, 1238, 1}, {0x01f0, 20, 2}, {0xffffffff, -1, 0}, {0x1e30, 1784, 1}, {0x03f0, 772, 1}, {0x0130, 261, 2}, {0x0542, 1385, 1}, {0xa65c, 2907, 1}, {0x1f83, 144, 2}, {0x0536, 1349, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab83, 1505, 1}, {0x053e, 1373, 1}, {0x10c83, 3366, 1}, {0x0538, 1355, 1}, {0x1eee, 2055, 1}, {0x04ee, 1235, 1}, {0x01ee, 480, 1}, {0x1f8d, 154, 2}, {0xffffffff, -1, 0}, {0x03ee, 875, 1}, {0xffffffff, -1, 0}, {0xab8d, 1535, 1}, {0xa78d, 643, 1}, {0x10c8d, 3396, 1}, {0x0534, 1343, 1}, {0x0181, 613, 1}, {0x1f81, 134, 2}, {0x013d, 258, 1}, {0x1f3d, 2163, 1}, {0xffffffff, -1, 0}, {0xab81, 1499, 1}, {0x017f, 52, 1}, {0x10c81, 3360, 1}, {0x2c7f, 583, 1}, {0x037f, 881, 1}, {0xff2d, 3195, 1}, {0xab7f, 1493, 1}, {0x1e74, 1887, 1}, {0x0474, 1064, 1}, {0x0174, 339, 1}, {0x1e3c, 1802, 1}, {0x0149, 46, 2}, {0x1f49, 2175, 1}, {0x1f3c, 2160, 1}, {0xab74, 1460, 1}, {0x0049, 3606, 1}, {0x0143, 267, 1}, {0x24cc, 2409, 1}, {0xa73c, 3012, 1}, {0xffffffff, -1, 0}, {0x0043, 6, 1}, {0x0141, 264, 1}, {0x24c6, 2391, 1}, {0x013b, 255, 1}, {0x1f3b, 2157, 1}, {0x0041, 0, 1}, {0x0139, 252, 1}, {0x1f39, 2151, 1}, {0x24c5, 2388, 1}, {0x24bb, 2358, 1}, {0x13fa, 1694, 1}, {0x053d, 1370, 1}, {0x24b9, 2352, 1}, {0x0429, 965, 1}, {0x2183, 2340, 1}, {0x1f29, 2127, 1}, {0x2c29, 2544, 1}, {0x24c3, 2382, 1}, {0x10427, 3354, 1}, {0x10425, 3348, 1}, {0x0427, 959, 1}, {0x0425, 953, 1}, {0xffffffff, -1, 0}, {0x2c27, 2538, 1}, {0x2c25, 2532, 1}, {0x0549, 1406, 1}, {0x053c, 1367, 1}, {0x10423, 3342, 1}, {0xffffffff, -1, 0}, {0x0423, 947, 1}, {0x0543, 1388, 1}, {0xffffffff, -1, 0}, {0x2c23, 2526, 1}, {0xff36, 3222, 1}, {0xffffffff, -1, 0}, {0x0541, 1382, 1}, {0x10421, 3336, 1}, {0x053b, 1364, 1}, {0x0421, 941, 1}, {0xff38, 3228, 1}, {0x0539, 1358, 1}, {0x2c21, 2520, 1}, {0x10419, 3312, 1}, {0x10417, 3306, 1}, {0x0419, 917, 1}, {0x0417, 911, 1}, {0x1f19, 2109, 1}, {0x2c19, 2496, 1}, {0x2c17, 2490, 1}, {0x023e, 2568, 1}, {0xff34, 3216, 1}, {0x10415, 3300, 1}, {0x10413, 3294, 1}, {0x0415, 905, 1}, {0x0413, 899, 1}, {0xffffffff, -1, 0}, {0x2c15, 2484, 1}, {0x2c13, 2478, 1}, {0xffffffff, -1, 0}, {0x24ce, 2415, 1}, {0x1040f, 3282, 1}, {0xffffffff, -1, 0}, {0x040f, 1031, 1}, {0xff30, 3204, 1}, {0x1f0f, 2103, 1}, {0x2c0f, 2466, 1}, {0x1040d, 3276, 1}, {0xffffffff, -1, 0}, {0x040d, 1025, 1}, {0x0147, 273, 1}, {0x1f0d, 2097, 1}, {0x2c0d, 2460, 1}, {0x1040b, 3270, 1}, {0x0047, 18, 1}, {0x040b, 1019, 1}, {0x0230, 571, 1}, {0x1f0b, 2091, 1}, {0x2c0b, 2454, 1}, {0x10409, 3264, 1}, {0x10405, 3252, 1}, {0x0409, 1013, 1}, {0x0405, 1001, 1}, {0x1f09, 2085, 1}, {0x2c09, 2448, 1}, {0x2c05, 2436, 1}, {0x10403, 3246, 1}, {0x10401, 3240, 1}, {0x0403, 995, 1}, {0x0401, 989, 1}, {0xffffffff, -1, 0}, {0x2c03, 2430, 1}, {0x2c01, 2424, 1}, {0x13f9, 1691, 1}, {0x042f, 983, 1}, {0xffffffff, -1, 0}, {0x1f2f, 2145, 1}, {0x1041f, 3330, 1}, {0xffffffff, -1, 0}, {0x041f, 935, 1}, {0x023d, 378, 1}, {0x10411, 3288, 1}, {0x2c1f, 2514, 1}, {0x0411, 893, 1}, {0x0547, 1400, 1}, {0xffffffff, -1, 0}, {0x2c11, 2472, 1}, {0x10407, 3258, 1}, {0xffffffff, -1, 0}, {0x0407, 1007, 1}, {0x24c1, 2376, 1}, {0xffffffff, -1, 0}, {0x2c07, 2442, 1}, {0xffffffff, -1, 0}, {0x13f8, 1688, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff39, 3231, 1}, {0xffffffff, -1, 0}, {0x0243, 354, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x0241, 586, 1}, {0xff29, 3183, 1}, {0x023b, 577, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff27, 3177, 1}, {0xff25, 3171, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff23, 3165, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff21, 3159, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb17, 117, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff2f, 3201, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb15, 113, 2}, {0xfb13, 121, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb05, 29, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb03, 0, 3}, {0xfb01, 8, 2} }; if (0 == 0) { int key = hash(&code); if (key <= MAX_HASH_VALUE && key >= 0) { OnigCodePoint gcode = wordlist[key].code; if (code == gcode && wordlist[key].index >= 0) return &wordlist[key]; } } return 0; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":400896,"input":"static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char *name, s[2]; const char *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, \/* ping_exclude_EXIF, *\/ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, \/* ping_exclude_iTXt, *\/ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, \/* ping_exclude_tRNS, *\/ ping_exclude_caNv, ping_exclude_zCCP, \/* hex-encoded iCCP *\/ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter WriteOnePNGImage()\"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); \/* Define these outside of the following \"if logging()\" block so they will * show in debuggers. *\/ *im_vers='\\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" IM version = %s\", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Libpng version = %s\", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Zlib version = %s\", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" running with %s\", zlib_runv); } } \/* Initialize some stuff *\/ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; \/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; *\/ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; \/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; *\/ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; \/* hex-encoded iCCP in zTXt *\/ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; \/* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some \"known invalid sRGB profiles\". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. *\/ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got a %lu-byte ICC profile (potentially sRGB)\", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" with crc=%8x\",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" It is sRGB with rendering intent = %s\", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Got %lu-byte ICC profile not recognized as sRGB\", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=UndefinedClass\"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=DirectClass\"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->storage_class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? \" image->taint=MagickTrue\": \" image->taint=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->gamma=%g\", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if ((image->storage_class != PseudoClass) && (image->colormap != (PixelInfo *) NULL)) { \/* Free the bogus colormap; it can cause trouble later *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Freeing bogus colormap\"); image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); \/* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. *\/ image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reducing PNG bit depth to 8 since this is a Q8 build.\"); image->depth=8; } #endif \/* Respect the -depth option *\/ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { \/* Scale to 4-bit *\/ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { \/* Scale to 2-bit *\/ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { \/* Scale to 1-bit *\/ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } \/* To do: set to next higher multiple of 8 *\/ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy *\/ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { \/* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. *\/ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { \/* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. *\/ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; if (image->depth != GetImageDepth(image,exception)) (void) SetImageDepth(image,image->depth,exception); for (j=0; j<6; j++) { \/* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. *\/ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *r; register Quantum *q; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter BUILD_PALETTE:\"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->columns=%.20g\",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->rows=%.20g\",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->alpha_trait=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Original colormap:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) MagickMin(image->colors,256); i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" (zero means unknown)\"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Regenerate the colormap\"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { r=GetVirtualPixels(image,0,y,image->columns,1,exception); if (r == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,r) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image,r,opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,r,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image,r,opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,r) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image,r,transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,r); ping_trans_color.green=(unsigned short) GetPixelGreen(image,r); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,r); ping_trans_color.gray=(unsigned short) GetPixelGray(image,r); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,r,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,r,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,r,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,r,semitransparent+i) && GetPixelAlpha(image,r) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image,r,semitransparent+i); } } } r+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { \/* Add the background color to the palette, if it * isn't already there. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Check colormap for background (%d,%d,%d)\", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } if (number_opaque < 259) { for (i=0; ibackground_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\",(int) i); } } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in the colormap to add background color\"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has more than 256 colors\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image has %d colors\",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) \/* We won't need this info *\/ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"incompatible colorspace\"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != GetPixelGreen(image,r) || GetPixelRed(image,r) != GetPixelBlue(image,r)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; \/* Worst case is black-and-white; we are looking at every * pixel twice. *\/ if (ping_have_non_bw == MagickFalse) { r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != 0 && GetPixelRed(image,r) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; \/* * Initialize image colormap. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Sort the new colormap\"); \/* Sort palette, transparent first *\/; n = 0; for (i=0; iping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_colors (%d) and n (%d) don't match\", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireImageColormap\"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d (%d)\", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Update the pixel indexes\"); } \/* Sync the pixel indices with the new colormap *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->colors=%d\", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" i (red,green,blue,alpha)\"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" %d (%d,%d,%d,%d)\", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent = %d\", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_transparent > 256\"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque = %d\", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_opaque > 256\"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent = %d\", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" number_semitransparent > 256\"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are black or white\"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" All pixels and the background are gray\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" At least one pixel or the background is non-gray\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Exit BUILD_PALETTE:\"); } if (mng_info->write_png8 == MagickFalse) break; \/* Make any reductions necessary for the PNG8 format *\/ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; \/* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. *\/ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Thresholding the alpha channel to binary\"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) < OpaqueAlpha\/2) { SetPixelViaPixelInfo(image,&image->background_color,q); SetPixelAlpha(image,TransparentAlpha,q); } else SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; icolormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha\/2 ? TransparentAlpha : OpaqueAlpha); } continue; } \/* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. *\/ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 4-4-4\"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 4-4-4\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR04PixelRGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 4-4-4\"); for (i=0; icolormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-3\"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-3-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR03RGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-3-1\"); for (i=0; icolormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the background color to 3-3-2\"); tried_332 = MagickTrue; \/* Red and green were already done so we only quantize the blue * channel *\/ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR02PixelBlue(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else \/* Should not reach this; colormap already exists and must be <= 256 *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Quantizing the colormap to 3-3-2-1\"); for (i=0; icolormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { \/* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red background colors to 3-3-2-1\"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Merging two dark red pixel colors to 3-3-2-1\"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,q)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,q)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,q)) == 0x00 && GetPixelAlpha(image,q) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; icolormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } \/* END OF BUILD_PALETTE *\/ \/* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. *\/ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } \/* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. *\/ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { \/* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. *\/ if (image_colors > 1) for (i=1; icolormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is not possible.\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Cheap transparency is possible.\"); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, \"Cannot write PNG8 or color-type 3; colormap is NULL\", \"`%s'\",IMimage->filename); return(MagickFalse); } \/* Allocate the PNG structures *\/ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { \/* PNG write failed. *\/ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf(\"PNG write has failed.\\n\"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } \/* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. *\/ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED \/* Allow benign errors *\/ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED \/* Reject images with too many rows or columns *\/ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif \/* PNG_SET_USER_LIMITS_SUPPORTED *\/ \/* Prepare PNG for writing. *\/ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED \/* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK *\/ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; \/* Adjust requested depth to next higher valid depth if necessary *\/ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" width=%.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" height=%.20g\",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_matte=%.20g\",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth=%.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative ping_bit_depth=%.20g\",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)\/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)\/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.\", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (1)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth=%d\",ping_bit_depth); } ping_have_bKGD = MagickTrue; } \/* Select the color type. *\/ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { \/* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. *\/ number_colors=image_colors; ping_have_tRNS=MagickFalse; \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors (%d)\", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 \" %3ld (%3d,%3d,%3d)\", #else \" %5ld (%5d,%5d,%5d)\", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { \/* Identify which colormap entry is transparent. *\/ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { \/* * Identify which colormap entry is the background color. *\/ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); } } } \/* end of write_png8 *\/ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else \/* mng_info->write_pngNN not specified *\/ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG colortype %d was specified:\",(int) ping_color_type); } else \/* write_png_colortype not specified *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selecting PNG colortype:\"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Selected PNG colortype=%d\",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { \/* DO SOMETHING *\/ png_error(ping,\"image has 0 colors\"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %.20g\",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG bit depth: %d\",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } (void) old_bit_depth; image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Tentative PNG color type: %s (%.20g)\", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_info->type: %.20g\",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image_depth: %.20g\",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->depth: %.20g\",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_bit_depth: %.20g\",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } \/* * Determine if there is any transparent color. *\/ if (number_transparent + number_semitransparent == 0) { \/* No transparent pixels are present. Change 4 or 6 to 0 or 2. *\/ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { \/* * Determine if there is one and only one transparent color * and if so if it is fully transparent. *\/ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; \/* changes 4 or 6 to 0 or 2 *\/ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (0)\"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { \/* Check if grayscale is reducible *\/ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { \/* Set image palette. *\/ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up PLTE chunk with %d colors\", number_colors); ping_have_PLTE=MagickTrue; } \/* color_type is PNG_COLOR_TYPE_PALETTE *\/ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { \/* * Set up trans_colors array. *\/ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color (1)\"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color from (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to (%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; \/* Adjust background and transparency samples in sub-8-bit grayscale files. *\/ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval\/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk (2)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background_color index is %d\", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Scaling ping_trans_color.gray from %d\", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval\/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" to %d\", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { \/* Identify which colormap entry is the background color. *\/ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk with index=%d\",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background =(%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else \/* Can't happen *\/ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No room in PLTE to add bKGD color\"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color type: %s (%d)\", PngColorTypeToString(ping_color_type), ping_color_type); \/* Initialize compression level and filtering. *\/ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up deflate compression\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression buffer size: 32768\"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression mem level: 9\"); png_set_compression_mem_level(ping, 9); \/* Untangle the \"-quality\" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type \"none\" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: \"LOCO\" filtering (intrapixel differing) if writing a MNG, otherwise \"none\". Did not work in IM-6.7.0-9 and earlier because of a missing \"else\". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates \"-define png:compression-strategy\", etc. *\/ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality\/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE \/* Z_RLE was added to zlib-1.2.0 *\/ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression level: %d\", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression strategy: %d\", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up filtering\"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: ADAPTIVE\"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: NONE\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Base filter method: %d\", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); \/* Bail out if cannot meet defined png:bit-depth or png:color-type *\/ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image has transparency but tRNS chunk was excluded\"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth=%u, Computed depth=%u\", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type=%u, Computed color type=%u\", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, \"Cannot write image with defined png:bit-depth or png:color-type.\"); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { \/* Add an opaque matte channel *\/ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Added an opaque matte channel\"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting ping_have_tRNS=MagickTrue.\"); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG header chunks\"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PLTE[%d] = (%d,%d,%d)\", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } \/* Only write the iCCP chunk if we are not writing the sRGB chunk. *\/ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,\"ICC\") == 0) || (LocaleCompare(name,\"ICM\") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up iCCP chunk\"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { \/* Do not write hex-encoded ICC chunk *\/ name=GetNextImageProfile(image); continue; } } #endif \/* WRITE_iCCP *\/ if (LocaleCompare(name,\"exif\") == 0) { \/* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk *\/ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up zTXt chunk with uuencoded %s profile\", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { \/* Note image rendering intent. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up sRGB chunk\"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { \/* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up gAMA chunk\"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { \/* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. *\/ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up cHRM chunk\"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up bKGD chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" background color = (%d,%d,%d)\", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" index = %d, gray=%d\", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up pHYs chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_resolution=%lu\", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" y_resolution=%lu\", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" unit_type=%lu\", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,\"png:tIME\"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,\"png:tIME\",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reset tIME in tainted image\"); timestamp=GetImageProperty(image,\"date:modify\",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,\"WriteBlob Failed\"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Calling png_set_tRNS with num_trans=%d\",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" tRNS color =(%d,%d,%d)\", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); \/* write orNT if image->orientation is defined *\/ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); \/* data length=1 *\/ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); \/* PNG uses Exif orientation values *\/ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; \/* write caNv chunk *\/ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); \/* data length=8 *\/ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up oFFs chunk with x=%d, y=%d, units=0\", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) \/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag *\/ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); \/* Allocate memory. *\/ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocating %.20g bytes of memory for pixels\",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,GetPixelChannels(image)* sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,\"Allocation of memory for pixels failed\"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(ping_pixels,0,rowbytes*GetPixelChannels(image)* sizeof(*ping_pixels)); \/* Initialize image scanlines. *\/ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,\"Memory allocation for quantum_info failed\"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) || ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse)) { \/* Palette, Bilevel, or Opaque Monochrome *\/ QuantumType quantum_type; register const Quantum *p; quantum_type=RedQuantum; if (mng_info->IsPalette) { quantum_type=GrayQuantum; if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) quantum_type=IndexQuantum; } SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { \/* Convert PseudoClass image to a PNG monochrome image. *\/ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (0)\"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,ping_pixels,exception); if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (1)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else \/* Not Palette, Bilevel, or Opaque Monochrome *\/ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY PNG pixels (2)\"); } else \/* PNG_COLOR_TYPE_GRAY_ALPHA *\/ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (2)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (2)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (3)\"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of pixels (3)\"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else \/* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) *\/ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is not GRAY or GRAY_ALPHA\",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA\", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing GRAY_ALPHA PNG pixels (4)\"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing row of non-gray pixels (4)\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ping_pixels[0]=%d,ping_pixels[1]=%d\", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Wrote PNG image data\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Width: %.20g\",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Height: %.20g\",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:bit-depth: %d\",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG bit-depth written: %d\",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Defined png:color-type: %d\",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG color-type written: %d\",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" PNG Interlace method: %d\",ping_interlace_method); } \/* Generate text chunks after IDAT. *\/ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); \/* Don't write any \"png:\" or \"jpeg:\" properties; those are just for * \"identify\" or for passing through to another JPEG *\/ if ((LocaleNCompare(property,\"png:\",4) != 0 && LocaleNCompare(property,\"jpeg:\",5) != 0) && \/* Suppress density and units if we wrote a pHYs chunk *\/ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,\"density\") != 0 || LocaleCompare(property,\"units\") != 0) && \/* Suppress the IM-generated Date:create and Date:modify *\/ (ping_exclude_date == MagickFalse || LocaleNCompare(property, \"Date:\",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Setting up text chunk\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" keyword: '%s'\",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } \/* write eXIf profile *\/ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { if (LocaleCompare(name,\"exif\") == 0) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Have eXIf profile\"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; \/* otherwise crashes *\/ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\\0' && *(data+5) == '\\0') { \/* skip the \"Exif\\0\\0\" JFIF Exif Header ID *\/ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing PNG end info\"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; \/* Write FRAM 4 with clipping boundaries followed by FRAM 1. *\/ (void) WriteBlobMSBULong(image,27L); \/* data length=27 *\/ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; \/* frame name separator (no name) *\/ chunk[6]=1; \/* flag for changing delay, for next frame only *\/ chunk[7]=0; \/* flag for changing frame timeout *\/ chunk[8]=1; \/* flag for changing frame clipping for next frame *\/ chunk[9]=0; \/* flag for changing frame sync_id *\/ PNGLong(chunk+10,(png_uint_32) (0L)); \/* temporary 0 delay *\/ chunk[14]=0; \/* clipping boundaries delta type *\/ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); \/* left cb *\/ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); \/* top cb *\/ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, \"Cannot convert GIF with disposal method 3 to MNG-LC\"); \/* Free PNG resources. *\/ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); \/* Store bit depth actually written *\/ s[0]=(char) ping_bit_depth; s[1]='\\0'; (void) SetImageProperty(IMimage,\"png:bit-depth-written\",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit WriteOnePNGImage()\"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif \/* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. *\/ return(MagickTrue); \/* End write one PNG image *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":301750,"input":"void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, \"EOS-1D\" }, { 0x167, \"EOS-1DS\" }, { 0x168, \"EOS 10D\" }, { 0x169, \"EOS-1D Mark III\" }, { 0x170, \"EOS 300D\" }, { 0x174, \"EOS-1D Mark II\" }, { 0x175, \"EOS 20D\" }, { 0x176, \"EOS 450D\" }, { 0x188, \"EOS-1Ds Mark II\" }, { 0x189, \"EOS 350D\" }, { 0x190, \"EOS 40D\" }, { 0x213, \"EOS 5D\" }, { 0x215, \"EOS-1Ds Mark III\" }, { 0x218, \"EOS 5D Mark II\" }, { 0x232, \"EOS-1D Mark II N\" }, { 0x234, \"EOS 30D\" }, { 0x236, \"EOS 400D\" }, { 0x250, \"EOS 7D\" }, { 0x252, \"EOS 500D\" }, { 0x254, \"EOS 1000D\" }, { 0x261, \"EOS 50D\" }, { 0x269, \"EOS-1D X\" }, { 0x270, \"EOS 550D\" }, { 0x281, \"EOS-1D Mark IV\" }, { 0x285, \"EOS 5D Mark III\" }, { 0x286, \"EOS 600D\" }, { 0x287, \"EOS 60D\" }, { 0x288, \"EOS 1100D\" }, { 0x289, \"EOS 7D Mark II\" }, { 0x301, \"EOS 650D\" }, { 0x302, \"EOS 6D\" }, { 0x324, \"EOS-1D C\" }, { 0x325, \"EOS 70D\" }, { 0x326, \"EOS 700D\" }, { 0x327, \"EOS 1200D\" }, { 0x331, \"EOS M\" }, { 0x335, \"EOS M2\" }, { 0x346, \"EOS 100D\" }, { 0x347, \"EOS 760D\" }, { 0x382, \"EOS 5DS\" }, { 0x393, \"EOS 750D\" }, { 0x401, \"EOS 5DS R\" }, }, sonique[] = { { 0x002, \"DSC-R1\" }, { 0x100, \"DSLR-A100\" }, { 0x101, \"DSLR-A900\" }, { 0x102, \"DSLR-A700\" }, { 0x103, \"DSLR-A200\" }, { 0x104, \"DSLR-A350\" }, { 0x105, \"DSLR-A300\" }, {262,\"DSLR-A900\"}, {263,\"DSLR-A380\"}, { 0x108, \"DSLR-A330\" }, { 0x109, \"DSLR-A230\" }, { 0x10a, \"DSLR-A290\" }, { 0x10d, \"DSLR-A850\" }, {270,\"DSLR-A850\"}, { 0x111, \"DSLR-A550\" }, { 0x112, \"DSLR-A500\" }, { 0x113, \"DSLR-A450\" }, { 0x116, \"NEX-5\" }, { 0x117, \"NEX-3\" }, { 0x118, \"SLT-A33\" }, { 0x119, \"SLT-A55V\" }, { 0x11a, \"DSLR-A560\" }, { 0x11b, \"DSLR-A580\" }, { 0x11c, \"NEX-C3\" }, { 0x11d, \"SLT-A35\" }, { 0x11e, \"SLT-A65V\" }, { 0x11f, \"SLT-A77V\" }, { 0x120, \"NEX-5N\" }, { 0x121, \"NEX-7\" }, {290,\"NEX-VG20E\"}, { 0x123, \"SLT-A37\" }, { 0x124, \"SLT-A57\" }, { 0x125, \"NEX-F3\" }, { 0x126, \"SLT-A99V\" }, { 0x127, \"NEX-6\" }, { 0x128, \"NEX-5R\" }, { 0x129, \"DSC-RX100\" }, { 0x12a, \"DSC-RX1\" }, {299,\"NEX-VG900\"}, {300,\"NEX-VG30E\"}, { 0x12e, \"ILCE-3000\" }, { 0x12f, \"SLT-A58\" }, { 0x131, \"NEX-3N\" }, { 0x132, \"ILCE-7\" }, { 0x133, \"NEX-5T\" }, { 0x134, \"DSC-RX100M2\" }, { 0x135, \"DSC-RX10\" }, { 0x136, \"DSC-RX1R\" }, { 0x137, \"ILCE-7R\" }, { 0x138, \"ILCE-6000\" }, { 0x139, \"ILCE-5000\" }, { 0x13d, \"DSC-RX100M3\" }, { 0x13e, \"ILCE-7S\" }, { 0x13f, \"ILCA-77M2\" }, { 0x153, \"ILCE-5100\" }, { 0x154, \"ILCE-7M2\" }, { 0x15a, \"ILCE-QX1\" }, }; static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-080C\" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-145C\" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-201C\" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-510C\" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,\"AVT\",\"F-510C\",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,\"AVT\",\"F-510C\" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,\"AVT\",\"F-510C\",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,\"AVT\",\"F-810C\" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,\"AgfaPhoto\",\"DC-833m\" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,\"Alcatel\",\"5035D\" }, \/\/ Android Raw dumps id start \/\/ File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 16424960,4208,3120, 0, 0, 0, 0, 1,0x16,0,0,\"Sony\",\"IMX135-mipi 13mp\" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,\"Sony\",\"IMX135-QCOM\" }, { 10223360,2608,1960, 0, 0, 0, 0, 1,0x94,0,0,\"Sony\",\"IMX072-mipi\" }, { 5107712,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,\"HTC\",\"UltraPixel\" }, { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,\"Samsung\",\"S3\" }, { 10223363,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,\"Samsung\",\"GalaxyNexus\" }, \/\/ Android Raw dumps id end { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,\"Baumer\",\"TXG14\",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,\"Canon\",\"PowerShot SD300\" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,\"Canon\",\"PowerShot A460\" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,\"Canon\",\"PowerShot A610\" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,\"Canon\",\"PowerShot A530\" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,\"Canon\",\"PowerShot S3 IS\" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,\"Canon\",\"PowerShot A620\" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,\"Canon\",\"PowerShot A470\" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,\"Canon\",\"PowerShot A720 IS\" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,\"Canon\",\"PowerShot A630\" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,\"Canon\",\"PowerShot A640\" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,\"Canon\",\"PowerShot A650\" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,\"Canon\",\"PowerShot SX110 IS\" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,\"Canon\",\"PowerShot SX120 IS\" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,\"Canon\",\"PowerShot SX20 IS\" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,\"Canon\",\"PowerShot SX220 HS\" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,\"Canon\",\"PowerShot SX30 IS\" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,\"Canon\",\"PowerShot A3300 IS\" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,\"Casio\",\"QV-2000UX\" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,\"Casio\",\"QV-3*00EX\" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,\"Casio\",\"QV-5700\" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,\"Casio\",\"EX-Z60\" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,\"Casio\",\"EX-S20\" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,\"Casio\",\"EX-S100\" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,\"Casio\",\"QV-R41\" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,\"Casio\",\"EX-P505\" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,\"Casio\",\"QV-R51\" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,\"Casio\",\"EX-Z50\" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,\"Casio\",\"EX-Z500\" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,\"Casio\",\"EX-Z55\" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,\"Casio\",\"EX-P600\" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,\"Casio\",\"EX-Z750\" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,\"Casio\",\"EX-Z75\" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,\"Casio\",\"EX-P700\" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,\"Casio\",\"EX-Z850\" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,\"Casio\",\"EX-Z8\" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,\"Casio\",\"EX-Z1050\" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,\"Casio\",\"EX-ZR100\" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,\"Casio\",\"QV-4000\" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,\"Creative\",\"PC-CAM 600\" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,\"DJI\" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,\"Matrix\" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,\"Foculus\",\"531C\" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,\"Generic\" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,\"Kodak\",\"DC20\" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,\"Kodak\",\"DC20\" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,\"Kodak\",\"DCS200\" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,\"Kodak\",\"C330\" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,\"Kodak\",\"C330\",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,\"Kodak\",\"C330\" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,\"Kodak\",\"C330\" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,\"Kodak\",\"C603\" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,\"Kodak\",\"C603\",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,\"Kodak\",\"C603\" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,\"Kodak\",\"C603\" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,\"Kodak\",\"12MP\" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,\"Kodak\",\"12MP\",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,\"Kodak\",\"12MP\" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,\"Kodak\",\"KAI-0340\" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,\"Lenovo\",\"A820\" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,\"Micron\",\"2010\",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,\"Minolta\",\"RD175\",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,\"Nikon\",\"E900\" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,\"Nikon\",\"E950\" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,\"Nikon\",\"E2100\" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,\"Nikon\",\"E990\" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,\"Nikon\",\"E3700\" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,\"Nikon\",\"E4500\" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,\"Nikon\",\"E4300\" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,\"Nikon\",\"E5000\" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,\"Nikon\",\"COOLPIX S6\" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,\"Olympus\",\"C770UZ\" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,\"Pentax\",\"Optio S\" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,\"Pentax\",\"Optio S\" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,\"Pentax\",\"Optio S4\" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,\"Pentax\",\"Optio 750Z\" }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,\"Pixelink\",\"A782\" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,\"RoverShot\",\"3320AF\" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,\"ST Micro\",\"STV680 VGA\" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,\"Samsung\",\"S85\" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,\"Samsung\",\"S85\" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,\"Samsung\",\"WB550\" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,\"Samsung\",\"WB550\" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,\"Sinar\",\"\",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,\"Sinar\",\"\",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,\"Sinar\",\"\",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,\"Sony\",\"XCD-SX910CR\" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,\"Sony\",\"XCD-SX910CR\" }, }; static const char *corp[] = { \"AgfaPhoto\", \"Canon\", \"Casio\", \"Epson\", \"Fujifilm\", \"Mamiya\", \"Minolta\", \"Motorola\", \"Kodak\", \"Konica\", \"Leica\", \"Nikon\", \"Nokia\", \"Olympus\", \"Pentax\", \"Phase One\", \"Ricoh\", \"Samsung\", \"Sigma\", \"Sinar\", \"Sony\" }; char head[32], *cp; int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; tiff_flip = flip = filters = UINT_MAX; \/* unknown *\/ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); fread (head, 1, 32, ifp); fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)\"MMMM\", 4)) || (cp = (char *) memmem (head, 32, (char*)\"IIII\", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,\"HEAPCCDR\",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = FixedLens; imgdata.lens.makernotes.LensMount = FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,\"\\xff\\xd8\\xff\\xe1\",4) && !memcmp (head+6,\"Exif\",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,\"ARECOYK\",7)) { strcpy (make, \"Contax\"); strcpy (model,\"N Digital\"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 60, SEEK_SET); FORC4 cam_mul[c ^ (c >> 1)] = get4(); } else if (!strcmp (head, \"PXN\")) { strcpy (make, \"Logitech\"); strcpy (model,\"Fotoman Pixtura\"); } else if (!strcmp (head, \"qktk\")) { strcpy (make, \"Apple\"); strcpy (model,\"QuickTake 100\"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, \"qktn\")) { strcpy (make, \"Apple\"); strcpy (model,\"QuickTake 150\"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,\"FUJIFILM\",8)) { fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4()) && 1; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,\"RIFF\",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,\"ftypqt \",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,\"\\0\\001\\0\\001\\0@\",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,\"NOKIARAW\",8)) { strcpy (make, \"NOKIA\"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); switch (tiff_bps = i*8 \/ (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i \/ (width * tiff_bps\/8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp (head,\"ARRI\",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, \"ARRI\"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,\"XPDS\",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,\"RED1\",4)) { strcpy (make, \"Red\"); strcpy (model,\"One\"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1\/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,\"DSC-Image\",9)) parse_rollei(); else if (!memcmp (head,\"PWAD\",4)) parse_sinar_ia(); else if (!memcmp (head,\"\\0MRM\",4)) parse_minolta(0); else if (!memcmp (head,\"FOVb\",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!imgdata.params.force_foveon_x3f) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,\"CI\",2)) parse_cine(); else for (zero_fsize=i=0; i < sizeof table \/ sizeof *table; i++) if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(make, \"Canon\")) { imgdata.lens.makernotes.CameraMount = FixedLens; imgdata.lens.makernotes.LensMount = FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 \/ (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)\/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); if (!(strncmp(model,\"ov\",2) && strncmp(model,\"RP_OV\",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,\"BRCMn\")) { strcpy (make, \"OmniVision\"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; } else is_raw = 0; } for (i=0; i < sizeof corp \/ sizeof *corp; i++) if (strcasestr (make, corp[i])) \/* Simplify company names *\/ strcpy (make, corp[i]); if ((!strcmp(make,\"Kodak\") || !strcmp(make,\"Leica\")) && ((cp = strcasestr(model,\" DIGITAL CAMERA\")) || (cp = strstr(model,\"FILE VERSION\")))) *cp = 0; if (!strncasecmp(model,\"PENTAX\",6)) strcpy (make, \"Pentax\"); cp = make + strlen(make); \/* Remove trailing spaces *\/ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; i = strlen(make); \/* Remove make from model *\/ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,\"FinePix \",8)) strcpy (model, model+8); if (!strncmp (model,\"Digital Camera \",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) \/* Pentax K10D and Samsung GX10 *\/ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) \/* Pentax K20D and Samsung GX20 *\/ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,\"K-r\") || !strcmp(model,\"K-x\"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,\"K-5\",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 4736 && !strcmp(model,\"K-7\")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,\"K-3\")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,\"645D\")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) \/* Ricoh GX200 *\/ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw = tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: \/* Compression not set, assuming uncompressed *\/ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strcmp(make, \"Canon\") && unique_id) { for (i = 0; i < sizeof unique \/ sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strcasecmp(make, \"Sony\") && unique_id) { for (i = 0; i < sizeof sonique \/ sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strcmp(make,\"Canon\") && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon \/ sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strcmp(make,\"Canon\") && unique_id) { for (i=0; i < sizeof unique \/ sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff (\"Canon\", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strcasecmp(make,\"Sony\") && unique_id) { for (i=0; i < sizeof sonique \/ sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff (\"Sony\", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strcmp(make,\"Nikon\")) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } \/* Set parameters based on camera name (for non-DNG files). *\/ if (!strcmp(model,\"KAI-0340\") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,\"C603\"); } if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!imgdata.params.force_foveon_x3f) simple_coeff(0); #endif } else if (!strcmp(make,\"Canon\") && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) SWAP(height,width); filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,\"PowerShot 600\")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,\"PowerShot A5\") || !strcmp(model,\"PowerShot A5 Zoom\")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256\/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,\"PowerShot A50\")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,\"PowerShot Pro70\")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,\"PowerShot Pro90 IS\") || !strcmp(model,\"PowerShot G1\")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,\"PowerShot A610\")) { if (canon_s2is()) strcpy (model+10, \"S2 IS\"); } else if (!strcmp(model,\"PowerShot SX220 HS\")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,\"PowerShot S120\")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,\"PowerShot G16\")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,\"PowerShot SX50 HS\")) { top_margin = 17; } else if (!strcmp(model,\"EOS D2000C\")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,\"D1\")) { cam_mul[0] *= 256\/527.0; cam_mul[2] *= 256\/317.0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.wb_applied = 1; #endif } else if (!strcmp(model,\"D1X\")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,\"D40X\") || !strcmp(model,\"D60\") || !strcmp(model,\"D80\") || !strcmp(model,\"D3000\")) { height -= 3; width -= 4; } else if (!strcmp(model,\"D3\") || !strcmp(model,\"D3S\") || !strcmp(model,\"D700\")) { width -= 4; left_margin = 2; } else if (!strcmp(model,\"D3100\")) { width -= 28; left_margin = 6; } else if (!strcmp(model,\"D5000\") || !strcmp(model,\"D90\")) { width -= 42; } else if (!strcmp(model,\"D5100\") || !strcmp(model,\"D7000\") || !strcmp(model,\"COOLPIX A\")) { width -= 44; } else if (!strcmp(model,\"D3200\") || !strncmp(model,\"D6\",2) || !strncmp(model,\"D800\",4)) { width -= 46; } else if (!strcmp(model,\"D4\") || !strcmp(model,\"Df\")) { width -= 52; left_margin = 2; } else if (!strncmp(model,\"D40\",3) || !strncmp(model,\"D50\",3) || !strncmp(model,\"D70\",3)) { width--; } else if (!strcmp(model,\"D100\")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,\"D200\")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,\"D2H\",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,\"D2X\",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,\"D300\",4)) { width -= 32; } else if (!strcmp(make,\"Nikon\") && raw_width == 4032) { if(!strcmp(model,\"COOLPIX P7700\")) { adobe_coeff (\"Nikon\",\"COOLPIX P7700\"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,\"COOLPIX P7800\")) { adobe_coeff (\"Nikon\",\"COOLPIX P7800\"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,\"COOLPIX P340\")) load_flags=0; } else if (!strncmp(model,\"COOLPIX P\",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && iso_speed >= 400) black = 255; } else if (!strncmp(model,\"1 \",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, \"E995\"); if (strcmp(model,\"E995\")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,\"E2500\"); if (!strcmp(model,\"E2500\")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,\"Optio 33WR\")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, \"Minolta\"); strcpy (model,\"DiMAGE Z2\"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, \"ISG\"); model[0] = 0; } } else if (!strcmp(make,\"Fujifilm\")) { if (!strcmp(model+7,\"S2Pro\")) { strcpy (model,\"S2Pro\"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (!strcmp(model,\"HS50EXR\") || !strcmp(model,\"F900EXR\")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,\"S5500\")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) xtrans[0][c] = xtrans_abs[(c\/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,\"KD-400Z\")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,\"KD-510Z\")) { goto konica_510z; } else if (!strcasecmp(make,\"Minolta\")) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,\"DiMAGE A\",8)) { if (!strcmp(model,\"DiMAGE A200\")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,\"ALPHA\",5) || !strncmp(model,\"DYNAX\",5) || !strncmp(model,\"MAXXUM\",6)) { sprintf (model+20, \"DYNAX %-10s\", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,\"DiMAGE G\",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,\"*ist D\")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,\"*ist DS\")) { height -= 2; } else if (!strcmp(make,\"Samsung\") && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strcmp(make,\"Samsung\") && !strcmp(model,\"NX3000\")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strcmp(make,\"Samsung\") && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strcmp(make,\"Samsung\") && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strcmp(make,\"Samsung\") && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strcmp(make,\"Samsung\") && raw_width == 6496) { filters = 0x61616161; } else if (!strcmp(model,\"EX1\")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,\"WB2000\")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,\"WB550\")) { strcpy (model, \"WB550\"); } else if (!strcmp(model,\"EX2F\")) { height = 3045; width = 4070; top_margin = 3; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,\"STV680 VGA\")) { black = 16; } else if (!strcmp(model,\"N95\")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,\"640x480\")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strcmp(make,\"Hasselblad\")) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strcasecmp(model,\"H3D\")) { adobe_coeff(\"Hasselblad\",\"H3DII-39\"); strcpy(model,\"H3DII-39\"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff(\"Hasselblad\",\"H4D-40\"); strcpy(model,\"H4D-40\"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff(\"Hasselblad\",\"H4D-60\"); strcpy(model,\"H4D-60\"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,\"H3DII-60\"); } } else if (raw_width == 4090) { strcpy (model, \"V96C\"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strcasecmp(model,\"H5D\")) { \/* H5D 50*\/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,\"H5D-50\"); } else if(!strcasecmp(model,\"H3D\")) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff(\"Hasselblad\",\"H3D-50\"); strcpy(model,\"H3D-50\"); } } else if (raw_width == 8374 && raw_height == 6304) { \/* H5D 50c*\/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,\"H5D-50c\"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strcmp(make,\"Sinar\")) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strcmp(make,\"Leaf\")) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, \"RBTG\"); strcpy (model, \"CatchLight\"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, \"DCB2\"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, \"Cantare\"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, \"Valeo 6\"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, \"Valeo 6\"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strcmp(make,\"Leica\") || !strcmp(make,\"Panasonic\")) { if ((flen - data_offset) \/ (raw_width*8\/7) == raw_height) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana \/ sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) \"\\x94\\x61\\x49\\x16\" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,\"C770UZ\")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strcmp(make,\"Olympus\")) { height += height & 1; if (exif_cfa) filters = exif_cfa; if( width == 9280) { left_margin = 12; top_margin = 12; width -= 64; height -= 24; load_flags |= 1024; } if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,\"E-300\") || !strcmp(model,\"E-500\")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,\"STYLUS1\")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,\"E-330\")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,\"SP550UZ\")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } } else if (!strcmp(model,\"N Digital\")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,\"DSC-F828\")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, \"RGBE\"); } else if (!strcmp(model,\"DSC-V3\")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strcmp(make,\"Sony\") && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strcmp(make,\"Sony\") && raw_width == 4288) { width -= 32; } else if (!strcmp(make,\"Sony\") && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strcmp(make,\"Sony\") && raw_width == 5504) { \/\/ ILCE-3000\/\/5000 width -= height > 3664 ? 8 : 32; } else if (!strcmp(make,\"Sony\") && raw_width == 6048) { width -= 24; if (strstr(model,\"RX1\") || strstr(model,\"A99\")) width -= 6; } else if (!strcmp(make,\"Sony\") && raw_width == 7392) { width -= 30; } else if (!strcmp(model,\"DSLR-A100\")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,\"DSLR-A350\")) { height -= 4; } else if (!strcmp(model,\"PIXL\")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,\"C603\") || !strcmp(model,\"C330\") || !strcmp(model,\"12MP\")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,\"C330\") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,\"EasyShare\",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strcasecmp(make,\"Kodak\")) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,\"NC2000\",6) || !strncmp(model,\"EOSDCS\",6) || !strncmp(model,\"DCS4\",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,\"DCS460A\")) goto bw; } else if (!strcmp(model,\"DCS660M\")) { black = 214; goto bw; } else if (!strcmp(model,\"DCS760M\")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,\"20X\")) strcpy (cdesc, \"MYCY\"); if (strstr(model,\"DC25\")) { strcpy (model, \"DC25\"); data_offset = 15424; } if (!strncmp(model,\"DC2\",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, \"DC290\", 5)) iso_speed = 100; if (!strncmp(model, \"DC280\", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) \/ (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) \/ (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,\"40\")) { strcpy (model, \"DC40\"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,\"DC50\")) { strcpy (model, \"DC50\"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,\"DC120\")) { strcpy (model, \"DC120\"); height = 976; width = 848; iso_speed=160; pixel_aspect = height\/0.75\/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,\"DCS200\")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,\"Fotoman Pixtura\")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,\"QuickTake\",9)) { if (head[5]) strcpy (model+10, \"200\"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strcmp(make,\"Rollei\") && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,\"GRAS-50S5C\")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,\"BB-500CL\")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,\"BB-500GE\")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,\"SVS625CL\")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } \/* Early reject for damaged images *\/ if (!load_raw || height < 22 || width < 22 || tiff_bps > 16 || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, \"%dx%d\", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: if ((use_camera_matrix & (use_camera_wb || dng_version)) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff (\"Apple\",\"Quicktake\"); if (fuji_width) { fuji_width = width >> !fuji_layout; if (~fuji_width & 1) filters = 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || tiff_bps > 16 || tiff_samples > 6 || colors > 4) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_(\"%s: You must link dcraw with %s!!\\n\"), ifname, \"libjasper\"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_(\"%s: You must link dcraw with %s!!\\n\"), ifname, \"libjpeg\"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? \"RGBG\":\"GMCY\"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":383762,"input":"int cli_scanpe(cli_ctx *ctx) { uint16_t e_magic; \/* DOS signature (\"MZ\") *\/ uint16_t nsections; uint32_t e_lfanew; \/* address of new exe header *\/ uint32_t ep, vep; \/* entry point (raw, virtual) *\/ uint8_t polipos = 0; time_t timestamp; struct pe_image_file_hdr file_hdr; union { struct pe_image_optional_hdr64 opt64; struct pe_image_optional_hdr32 opt32; } pe_opt; struct pe_image_section_hdr *section_hdr; char sname[9], epbuff[4096], *tempfile; uint32_t epsize; ssize_t bytes, at; unsigned int i, j, found, upx_success = 0, min = 0, max = 0, err, overlays = 0, rescan = 1; unsigned int ssize = 0, dsize = 0, dll = 0, pe_plus = 0, corrupted_cur; int (*upxfn)(const char *, uint32_t, char *, uint32_t *, uint32_t, uint32_t, uint32_t) = NULL; const char *src = NULL; char *dest = NULL; int ndesc, ret = CL_CLEAN, upack = 0, native=0; size_t fsize; uint32_t valign, falign, hdr_size; struct cli_exe_section *exe_sections; char timestr[32]; struct pe_image_data_dir *dirs; struct cli_bc_ctx *bc_ctx; fmap_t *map; struct cli_pe_hook_data pedata; #ifdef HAVE__INTERNAL__SHA_COLLECT int sha_collect = ctx->sha_collect; #endif const char *archtype=NULL, *subsystem=NULL; uint32_t viruses_found = 0; #if HAVE_JSON int toval = 0; struct json_object *pe_json=NULL; char jsonbuf[128]; #endif if(!ctx) { cli_errmsg(\"cli_scanpe: ctx == NULL\\n\"); return CL_ENULLARG; } #if HAVE_JSON if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) { return CL_ETIMEOUT; } if (ctx->options & CL_SCAN_FILE_PROPERTIES) { pe_json = get_pe_property(ctx); } #endif map = *ctx->fmap; if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic)) { cli_dbgmsg(\"Can't read DOS signature\\n\"); return CL_CLEAN; } if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) { cli_dbgmsg(\"Invalid DOS signature\\n\"); return CL_CLEAN; } if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) { cli_dbgmsg(\"Can't read new header address\\n\"); \/* truncated header? *\/ if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } e_lfanew = EC32(e_lfanew); cli_dbgmsg(\"e_lfanew == %d\\n\", e_lfanew); if(!e_lfanew) { cli_dbgmsg(\"Not a PE file\\n\"); return CL_CLEAN; } if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) { \/* bad information in e_lfanew - probably not a PE file *\/ cli_dbgmsg(\"Can't read file header\\n\"); return CL_CLEAN; } if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) { cli_dbgmsg(\"Invalid PE signature (probably NE file)\\n\"); return CL_CLEAN; } if(EC16(file_hdr.Characteristics) & 0x2000) { #if HAVE_JSON if ((pe_json)) cli_jsonstr(pe_json, \"Type\", \"DLL\"); #endif cli_dbgmsg(\"File type: DLL\\n\"); dll = 1; } else if(EC16(file_hdr.Characteristics) & 0x01) { #if HAVE_JSON if ((pe_json)) cli_jsonstr(pe_json, \"Type\", \"EXE\"); #endif cli_dbgmsg(\"File type: Executable\\n\"); } switch(EC16(file_hdr.Machine)) { case 0x0: archtype = \"Unknown\"; break; case 0x14c: archtype = \"80386\"; break; case 0x14d: archtype = \"80486\"; break; case 0x14e: archtype = \"80586\"; break; case 0x160: archtype = \"R30000 (big-endian)\"; break; case 0x162: archtype = \"R3000\"; break; case 0x166: archtype = \"R4000\"; break; case 0x168: archtype = \"R10000\"; break; case 0x184: archtype = \"DEC Alpha AXP\"; break; case 0x284: archtype = \"DEC Alpha AXP 64bit\"; break; case 0x1f0: archtype = \"PowerPC\"; break; case 0x200: archtype = \"IA64\"; break; case 0x268: archtype = \"M68k\"; break; case 0x266: archtype = \"MIPS16\"; break; case 0x366: archtype = \"MIPS+FPU\"; break; case 0x466: archtype = \"MIPS16+FPU\"; break; case 0x1a2: archtype = \"Hitachi SH3\"; break; case 0x1a3: archtype = \"Hitachi SH3-DSP\"; break; case 0x1a4: archtype = \"Hitachi SH3-E\"; break; case 0x1a6: archtype = \"Hitachi SH4\"; break; case 0x1a8: archtype = \"Hitachi SH5\"; break; case 0x1c0: archtype = \"ARM\"; break; case 0x1c2: archtype = \"THUMB\"; break; case 0x1d3: archtype = \"AM33\"; break; case 0x520: archtype = \"Infineon TriCore\"; break; case 0xcef: archtype = \"CEF\"; break; case 0xebc: archtype = \"EFI Byte Code\"; break; case 0x9041: archtype = \"M32R\"; break; case 0xc0ee: archtype = \"CEEE\"; break; case 0x8664: archtype = \"AMD64\"; break; default: archtype = \"Unknown\"; } if ((archtype)) { cli_dbgmsg(\"Machine type: %s\\n\", archtype); #if HAVE_JSON cli_jsonstr(pe_json, \"ArchType\", archtype); #endif } nsections = EC16(file_hdr.NumberOfSections); if(nsections < 1 || nsections > 96) { #if HAVE_JSON pe_add_heuristic_property(ctx, \"BadNumberOfSections\"); #endif if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } if(!ctx->corrupted_input) { if(nsections) cli_warnmsg(\"PE file contains %d sections\\n\", nsections); else cli_warnmsg(\"PE file contains no sections\\n\"); } return CL_CLEAN; } cli_dbgmsg(\"NumberOfSections: %d\\n\", nsections); timestamp = (time_t) EC32(file_hdr.TimeDateStamp); cli_dbgmsg(\"TimeDateStamp: %s\", cli_ctime(×tamp, timestr, sizeof(timestr))); #if HAVE_JSON cli_jsonstr(pe_json, \"TimeDateStamp\", cli_ctime(×tamp, timestr, sizeof(timestr))); #endif cli_dbgmsg(\"SizeOfOptionalHeader: %x\\n\", EC16(file_hdr.SizeOfOptionalHeader)); #if HAVE_JSON cli_jsonint(pe_json, \"SizeOfOptionalHeader\", EC16(file_hdr.SizeOfOptionalHeader)); #endif if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) { #if HAVE_JSON pe_add_heuristic_property(ctx, \"BadOptionalHeaderSize\"); #endif cli_dbgmsg(\"SizeOfOptionalHeader too small\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at = e_lfanew + sizeof(struct pe_image_file_hdr); if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg(\"Can't read optional file header\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_optional_hdr32); \/* This will be a chicken and egg problem until we drop 9x *\/ if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) { #if HAVE_JSON pe_add_heuristic_property(ctx, \"BadOptionalHeaderSizePE32Plus\"); #endif if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) { \/* FIXME: need to play around a bit more with xp64 *\/ cli_dbgmsg(\"Incorrect SizeOfOptionalHeader for PE32+\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } pe_plus = 1; } if(!pe_plus) { \/* PE *\/ if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) { \/* Seek to the end of the long header *\/ at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32); } if(DCONF & PE_CONF_UPACK) upack = (EC16(file_hdr.SizeOfOptionalHeader)==0x148); vep = EC32(optional_hdr32.AddressOfEntryPoint); hdr_size = EC32(optional_hdr32.SizeOfHeaders); cli_dbgmsg(\"File format: PE\\n\"); cli_dbgmsg(\"MajorLinkerVersion: %d\\n\", optional_hdr32.MajorLinkerVersion); cli_dbgmsg(\"MinorLinkerVersion: %d\\n\", optional_hdr32.MinorLinkerVersion); cli_dbgmsg(\"SizeOfCode: 0x%x\\n\", EC32(optional_hdr32.SizeOfCode)); cli_dbgmsg(\"SizeOfInitializedData: 0x%x\\n\", EC32(optional_hdr32.SizeOfInitializedData)); cli_dbgmsg(\"SizeOfUninitializedData: 0x%x\\n\", EC32(optional_hdr32.SizeOfUninitializedData)); cli_dbgmsg(\"AddressOfEntryPoint: 0x%x\\n\", vep); cli_dbgmsg(\"BaseOfCode: 0x%x\\n\", EC32(optional_hdr32.BaseOfCode)); cli_dbgmsg(\"SectionAlignment: 0x%x\\n\", EC32(optional_hdr32.SectionAlignment)); cli_dbgmsg(\"FileAlignment: 0x%x\\n\", EC32(optional_hdr32.FileAlignment)); cli_dbgmsg(\"MajorSubsystemVersion: %d\\n\", EC16(optional_hdr32.MajorSubsystemVersion)); cli_dbgmsg(\"MinorSubsystemVersion: %d\\n\", EC16(optional_hdr32.MinorSubsystemVersion)); cli_dbgmsg(\"SizeOfImage: 0x%x\\n\", EC32(optional_hdr32.SizeOfImage)); cli_dbgmsg(\"SizeOfHeaders: 0x%x\\n\", hdr_size); cli_dbgmsg(\"NumberOfRvaAndSizes: %d\\n\", EC32(optional_hdr32.NumberOfRvaAndSizes)); dirs = optional_hdr32.DataDirectory; #if HAVE_JSON cli_jsonint(pe_json, \"MajorLinkerVersion\", optional_hdr32.MajorLinkerVersion); cli_jsonint(pe_json, \"MinorLinkerVersion\", optional_hdr32.MinorLinkerVersion); cli_jsonint(pe_json, \"SizeOfCode\", EC32(optional_hdr32.SizeOfCode)); cli_jsonint(pe_json, \"SizeOfInitializedData\", EC32(optional_hdr32.SizeOfInitializedData)); cli_jsonint(pe_json, \"SizeOfUninitializedData\", EC32(optional_hdr32.SizeOfUninitializedData)); cli_jsonint(pe_json, \"NumberOfRvaAndSizes\", EC32(optional_hdr32.NumberOfRvaAndSizes)); cli_jsonint(pe_json, \"MajorSubsystemVersion\", EC16(optional_hdr32.MajorSubsystemVersion)); cli_jsonint(pe_json, \"MinorSubsystemVersion\", EC16(optional_hdr32.MinorSubsystemVersion)); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", EC32(optional_hdr32.BaseOfCode)); cli_jsonstr(pe_json, \"BaseOfCode\", jsonbuf); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", EC32(optional_hdr32.SectionAlignment)); cli_jsonstr(pe_json, \"SectionAlignment\", jsonbuf); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", EC32(optional_hdr32.FileAlignment)); cli_jsonstr(pe_json, \"FileAlignment\", jsonbuf); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", EC32(optional_hdr32.SizeOfImage)); cli_jsonstr(pe_json, \"SizeOfImage\", jsonbuf); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", hdr_size); cli_jsonstr(pe_json, \"SizeOfHeaders\", jsonbuf); #endif } else { \/* PE+ *\/ \/* read the remaining part of the header *\/ if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg(\"Can't read optional file header\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32); vep = EC32(optional_hdr64.AddressOfEntryPoint); hdr_size = EC32(optional_hdr64.SizeOfHeaders); cli_dbgmsg(\"File format: PE32+\\n\"); cli_dbgmsg(\"MajorLinkerVersion: %d\\n\", optional_hdr64.MajorLinkerVersion); cli_dbgmsg(\"MinorLinkerVersion: %d\\n\", optional_hdr64.MinorLinkerVersion); cli_dbgmsg(\"SizeOfCode: 0x%x\\n\", EC32(optional_hdr64.SizeOfCode)); cli_dbgmsg(\"SizeOfInitializedData: 0x%x\\n\", EC32(optional_hdr64.SizeOfInitializedData)); cli_dbgmsg(\"SizeOfUninitializedData: 0x%x\\n\", EC32(optional_hdr64.SizeOfUninitializedData)); cli_dbgmsg(\"AddressOfEntryPoint: 0x%x\\n\", vep); cli_dbgmsg(\"BaseOfCode: 0x%x\\n\", EC32(optional_hdr64.BaseOfCode)); cli_dbgmsg(\"SectionAlignment: 0x%x\\n\", EC32(optional_hdr64.SectionAlignment)); cli_dbgmsg(\"FileAlignment: 0x%x\\n\", EC32(optional_hdr64.FileAlignment)); cli_dbgmsg(\"MajorSubsystemVersion: %d\\n\", EC16(optional_hdr64.MajorSubsystemVersion)); cli_dbgmsg(\"MinorSubsystemVersion: %d\\n\", EC16(optional_hdr64.MinorSubsystemVersion)); cli_dbgmsg(\"SizeOfImage: 0x%x\\n\", EC32(optional_hdr64.SizeOfImage)); cli_dbgmsg(\"SizeOfHeaders: 0x%x\\n\", hdr_size); cli_dbgmsg(\"NumberOfRvaAndSizes: %d\\n\", EC32(optional_hdr64.NumberOfRvaAndSizes)); dirs = optional_hdr64.DataDirectory; #if HAVE_JSON cli_jsonint(pe_json, \"MajorLinkerVersion\", optional_hdr64.MajorLinkerVersion); cli_jsonint(pe_json, \"MinorLinkerVersion\", optional_hdr64.MinorLinkerVersion); cli_jsonint(pe_json, \"SizeOfCode\", EC32(optional_hdr64.SizeOfCode)); cli_jsonint(pe_json, \"SizeOfInitializedData\", EC32(optional_hdr64.SizeOfInitializedData)); cli_jsonint(pe_json, \"SizeOfUninitializedData\", EC32(optional_hdr64.SizeOfUninitializedData)); cli_jsonint(pe_json, \"NumberOfRvaAndSizes\", EC32(optional_hdr64.NumberOfRvaAndSizes)); cli_jsonint(pe_json, \"MajorSubsystemVersion\", EC16(optional_hdr64.MajorSubsystemVersion)); cli_jsonint(pe_json, \"MinorSubsystemVersion\", EC16(optional_hdr64.MinorSubsystemVersion)); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", EC32(optional_hdr64.BaseOfCode)); cli_jsonstr(pe_json, \"BaseOfCode\", jsonbuf); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", EC32(optional_hdr64.SectionAlignment)); cli_jsonstr(pe_json, \"SectionAlignment\", jsonbuf); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", EC32(optional_hdr64.FileAlignment)); cli_jsonstr(pe_json, \"FileAlignment\", jsonbuf); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", EC32(optional_hdr64.SizeOfImage)); cli_jsonstr(pe_json, \"SizeOfImage\", jsonbuf); snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", hdr_size); cli_jsonstr(pe_json, \"SizeOfHeaders\", jsonbuf); #endif } #if HAVE_JSON if (ctx->options & CL_SCAN_FILE_PROPERTIES) { snprintf(jsonbuf, sizeof(jsonbuf), \"0x%x\", vep); cli_jsonstr(pe_json, \"EntryPoint\", jsonbuf); } #endif switch(pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)) { case 0: subsystem = \"Unknown\"; break; case 1: subsystem = \"Native (svc)\"; native = 1; break; case 2: subsystem = \"Win32 GUI\"; break; case 3: subsystem = \"Win32 console\"; break; case 5: subsystem = \"OS\/2 console\"; break; case 7: subsystem = \"POSIX console\"; break; case 8: subsystem = \"Native Win9x driver\"; break; case 9: subsystem = \"WinCE GUI\"; break; case 10: subsystem = \"EFI application\"; break; case 11: subsystem = \"EFI driver\"; break; case 12: subsystem = \"EFI runtime driver\"; break; case 13: subsystem = \"EFI ROM image\"; break; case 14: subsystem = \"Xbox\"; break; case 16: subsystem = \"Boot application\"; break; default: subsystem = \"Unknown\"; } cli_dbgmsg(\"Subsystem: %s\\n\", subsystem); #if HAVE_JSON cli_jsonstr(pe_json, \"Subsystem\", subsystem); #endif cli_dbgmsg(\"------------------------------------\\n\"); if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment)) || (pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment))%0x1000)) { cli_dbgmsg(\"Bad virtual alignemnt\\n\"); cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment)) || (pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment))%0x200)) { cli_dbgmsg(\"Bad file alignemnt\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); return CL_VIRUS; } fsize = map->len; section_hdr = (struct pe_image_section_hdr *) cli_calloc(nsections, sizeof(struct pe_image_section_hdr)); if(!section_hdr) { cli_dbgmsg(\"Can't allocate memory for section headers\\n\"); return CL_EMEM; } exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section)); if(!exe_sections) { cli_dbgmsg(\"Can't allocate memory for section headers\\n\"); free(section_hdr); return CL_EMEM; } valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment); falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment); if(fmap_readn(map, section_hdr, at, sizeof(struct pe_image_section_hdr)*nsections) != (int)(nsections*sizeof(struct pe_image_section_hdr))) { cli_dbgmsg(\"Can't read section header\\n\"); cli_dbgmsg(\"Possibly broken PE file\\n\"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_section_hdr)*nsections; for(i = 0; falign!=0x200 && i= fsize) { cli_dbgmsg(\"Broken PE file - Section %d starts or exists beyond the end of file (Offset@ %lu, Total filesize %lu)\\n\", i, (unsigned long)exe_sections[i].raw, (unsigned long)fsize); if (nsections == 1) { free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; \/* no ninjas to see here! move along! *\/ } for (j=i; j < nsections-1; j++) memcpy(&exe_sections[j], &exe_sections[j+1], sizeof(struct cli_exe_section)); for (j=i; j < nsections-1; j++) memcpy(§ion_hdr[j], §ion_hdr[j+1], sizeof(struct pe_image_section_hdr)); nsections--; rescan=1; break; } } } } for(i = 0; i < nsections; i++) { strncpy(sname, (char *) section_hdr[i].Name, 8); sname[8] = 0; #if HAVE_JSON add_section_info(ctx, &exe_sections[i]); if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) { free(section_hdr); free(exe_sections); return CL_ETIMEOUT; } #endif if (!exe_sections[i].vsz && exe_sections[i].rsz) exe_sections[i].vsz=PESALIGN(exe_sections[i].ursz, valign); if (exe_sections[i].rsz && fsize>exe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz)) exe_sections[i].rsz = fsize - exe_sections[i].raw; cli_dbgmsg(\"Section %d\\n\", i); cli_dbgmsg(\"Section name: %s\\n\", sname); cli_dbgmsg(\"Section data (from headers - in memory)\\n\"); cli_dbgmsg(\"VirtualSize: 0x%x 0x%x\\n\", exe_sections[i].uvsz, exe_sections[i].vsz); cli_dbgmsg(\"VirtualAddress: 0x%x 0x%x\\n\", exe_sections[i].urva, exe_sections[i].rva); cli_dbgmsg(\"SizeOfRawData: 0x%x 0x%x\\n\", exe_sections[i].ursz, exe_sections[i].rsz); cli_dbgmsg(\"PointerToRawData: 0x%x 0x%x\\n\", exe_sections[i].uraw, exe_sections[i].raw); if(exe_sections[i].chr & 0x20) { cli_dbgmsg(\"Section contains executable code\\n\"); if(exe_sections[i].vsz < exe_sections[i].rsz) { cli_dbgmsg(\"Section contains free space\\n\"); \/* cli_dbgmsg(\"Dumping %d bytes\\n\", section_hdr.SizeOfRawData - section_hdr.VirtualSize); ddump(desc, section_hdr.PointerToRawData + section_hdr.VirtualSize, section_hdr.SizeOfRawData - section_hdr.VirtualSize, cli_gentemp(NULL)); *\/ } } if(exe_sections[i].chr & 0x20000000) cli_dbgmsg(\"Section's memory is executable\\n\"); if(exe_sections[i].chr & 0x80000000) cli_dbgmsg(\"Section's memory is writeable\\n\"); if (DETECT_BROKEN_PE && (!valign || (exe_sections[i].urva % valign))) { \/* Bad virtual alignment *\/ cli_dbgmsg(\"VirtualAddress is misaligned\\n\"); cli_dbgmsg(\"------------------------------------\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } if (exe_sections[i].rsz) { \/* Don't bother with virtual only sections *\/ if(SCAN_ALGO && (DCONF & PE_CONF_POLIPOS) && !*sname && exe_sections[i].vsz > 40000 && exe_sections[i].vsz < 70000 && exe_sections[i].chr == 0xe0000060) polipos = i; \/* check hash section sigs *\/ if((DCONF & PE_CONF_MD5SECT) && ctx->engine->hm_mdb) { ret = scan_pe_mdb(ctx, &exe_sections[i]); if (ret != CL_CLEAN) { if (ret != CL_VIRUS) cli_errmsg(\"scan_pe: scan_pe_mdb failed: %s!\\n\", cl_strerror(ret)); cli_dbgmsg(\"------------------------------------\\n\"); free(section_hdr); free(exe_sections); return ret; } } } cli_dbgmsg(\"------------------------------------\\n\"); if (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) { cli_dbgmsg(\"Found PE values with sign bit set\\n\"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } if(!i) { if (DETECT_BROKEN_PE && exe_sections[i].urva!=hdr_size) { \/* Bad first section RVA *\/ cli_dbgmsg(\"First section is in the wrong place\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } min = exe_sections[i].rva; max = exe_sections[i].rva + exe_sections[i].rsz; } else { if (DETECT_BROKEN_PE && exe_sections[i].urva - exe_sections[i-1].urva != exe_sections[i-1].vsz) { \/* No holes, no overlapping, no virtual disorder *\/ cli_dbgmsg(\"Virtually misplaced section (wrong order, overlapping, non contiguous)\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } if(exe_sections[i].rva < min) min = exe_sections[i].rva; if(exe_sections[i].rva + exe_sections[i].rsz > max) { max = exe_sections[i].rva + exe_sections[i].rsz; overlays = exe_sections[i].raw + exe_sections[i].rsz; } } } free(section_hdr); if(!(ep = cli_rawaddr(vep, exe_sections, nsections, &err, fsize, hdr_size)) && err) { cli_dbgmsg(\"EntryPoint out of file\\n\"); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } #if HAVE_JSON cli_jsonint(pe_json, \"EntryPointOffset\", ep); if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) { return CL_ETIMEOUT; } #endif cli_dbgmsg(\"EntryPoint offset: 0x%x (%d)\\n\", ep, ep); if(pe_plus) { \/* Do not continue for PE32+ files *\/ free(exe_sections); return CL_CLEAN; } epsize = fmap_readn(map, epbuff, ep, 4096); \/* Disasm scan disabled since it's now handled by the bytecode *\/ \/* CLI_UNPTEMP(\"DISASM\",(exe_sections,0)); *\/ \/* if(disasmbuf((unsigned char*)epbuff, epsize, ndesc)) *\/ \/* ret = cli_scandesc(ndesc, ctx, CL_TYPE_PE_DISASM, 1, NULL, AC_SCAN_VIR); *\/ \/* close(ndesc); *\/ \/* CLI_TMPUNLK(); *\/ \/* free(tempfile); *\/ \/* if(ret == CL_VIRUS) { *\/ \/* free(exe_sections); *\/ \/* return ret; *\/ \/* } *\/ if(overlays) { int overlays_sz = fsize - overlays; if(overlays_sz > 0) { ret = cli_scanishield(ctx, overlays, overlays_sz); if(ret != CL_CLEAN) { free(exe_sections); return ret; } } } pedata.nsections = nsections; pedata.ep = ep; pedata.offset = 0; memcpy(&pedata.file_hdr, &file_hdr, sizeof(file_hdr)); memcpy(&pedata.opt32, &pe_opt.opt32, sizeof(pe_opt.opt32)); memcpy(&pedata.opt64, &pe_opt.opt64, sizeof(pe_opt.opt64)); memcpy(&pedata.dirs, dirs, sizeof(pedata.dirs)); pedata.e_lfanew = e_lfanew; pedata.overlays = overlays; pedata.overlays_sz = fsize - overlays; pedata.hdr_size = hdr_size; \/* Bytecode BC_PE_ALL hook *\/ bc_ctx = cli_bytecode_context_alloc(); if (!bc_ctx) { cli_errmsg(\"cli_scanpe: can't allocate memory for bc_ctx\\n\"); free(exe_sections); return CL_EMEM; } cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections); cli_bytecode_context_setctx(bc_ctx, ctx); ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_ALL, map); switch (ret) { case CL_ENULLARG: cli_warnmsg(\"cli_scanpe: NULL argument supplied\\n\"); break; case CL_VIRUS: case CL_BREAK: free(exe_sections); cli_bytecode_context_destroy(bc_ctx); return ret == CL_VIRUS ? CL_VIRUS : CL_CLEAN; } cli_bytecode_context_destroy(bc_ctx); \/* Attempt to detect some popular polymorphic viruses *\/ \/* W32.Parite.B *\/ if(SCAN_ALGO && (DCONF & PE_CONF_PARITE) && !dll && epsize == 4096 && ep == exe_sections[nsections - 1].raw) { const char *pt = cli_memstr(epbuff, 4040, \"\\x47\\x65\\x74\\x50\\x72\\x6f\\x63\\x41\\x64\\x64\\x72\\x65\\x73\\x73\\x00\", 15); if(pt) { pt += 15; if((((uint32_t)cli_readint32(pt) ^ (uint32_t)cli_readint32(pt + 4)) == 0x505a4f) && (((uint32_t)cli_readint32(pt + 8) ^ (uint32_t)cli_readint32(pt + 12)) == 0xffffb) && (((uint32_t)cli_readint32(pt + 16) ^ (uint32_t)cli_readint32(pt + 20)) == 0xb8)) { cli_append_virus(ctx,\"Heuristics.W32.Parite.B\"); if (!SCAN_ALL) { free(exe_sections); return CL_VIRUS; } viruses_found++; } } } \/* Kriz *\/ if(SCAN_ALGO && (DCONF & PE_CONF_KRIZ) && epsize >= 200 && CLI_ISCONTAINED(exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz, ep, 0x0fd2) && epbuff[1]=='\\x9c' && epbuff[2]=='\\x60') { enum {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSXORPRFX,KZSXOR,KZSDDELTA,KZSLOOP,KZSTOP}; uint8_t kzs[] = {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSTRASH,KZSXORPRFX,KZSXOR,KZSTRASH,KZSDDELTA,KZSTRASH,KZSLOOP,KZSTOP}; uint8_t *kzstate = kzs; uint8_t *kzcode = (uint8_t *)epbuff + 3; uint8_t kzdptr=0xff, kzdsize=0xff; int kzlen = 197, kzinitlen=0xffff, kzxorlen=-1; cli_dbgmsg(\"in kriz\\n\"); while(*kzstate!=KZSTOP) { uint8_t op; if(kzlen<=6) break; op = *kzcode++; kzlen--; switch (*kzstate) { case KZSTRASH: case KZSGETSIZE: { int opsz=0; switch(op) { case 0x81: kzcode+=5; kzlen-=5; break; case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbd: case 0xbe: case 0xbf: if(*kzstate==KZSGETSIZE && cli_readint32(kzcode)==0x0fd2) { kzinitlen = kzlen-5; kzdsize=op-0xb8; kzstate++; op=4; \/* fake the register to avoid breaking out *\/ cli_dbgmsg(\"kriz: using #%d as size counter\\n\", kzdsize); } opsz=4; case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4d: case 0x4e: case 0x4f: op&=7; if(op!=kzdptr && op!=kzdsize) { kzcode+=opsz; kzlen-=opsz; break; } default: kzcode--; kzlen++; kzstate++; } break; } case KZSCDELTA: if(op==0xe8 && (uint32_t)cli_readint32(kzcode) < 0xff) { kzlen-=*kzcode+4; kzcode+=*kzcode+4; kzstate++; } else *kzstate=KZSTOP; break; case KZSPDELTA: if((op&0xf8)==0x58 && (kzdptr=op-0x58)!=4) { kzstate++; cli_dbgmsg(\"kriz: using #%d as pointer\\n\", kzdptr); } else *kzstate=KZSTOP; break; case KZSXORPRFX: kzstate++; if(op==0x3e) break; case KZSXOR: if (op==0x80 && *kzcode==kzdptr+0xb0) { kzxorlen=kzlen; kzcode+=+6; kzlen-=+6; kzstate++; } else *kzstate=KZSTOP; break; case KZSDDELTA: if (op==kzdptr+0x48) kzstate++; else *kzstate=KZSTOP; break; case KZSLOOP: if (op==kzdsize+0x48 && *kzcode==0x75 && kzlen-(int8_t)kzcode[1]-3<=kzinitlen && kzlen-(int8_t)kzcode[1]>=kzxorlen) { cli_append_virus(ctx,\"Heuristics.W32.Kriz\"); if (!SCAN_ALL) { free(exe_sections); return CL_VIRUS; } viruses_found++; } cli_dbgmsg(\"kriz: loop out of bounds, corrupted sample?\\n\"); kzstate++; } } } \/* W32.Magistr.A\/B *\/ if(SCAN_ALGO && (DCONF & PE_CONF_MAGISTR) && !dll && (nsections>1) && (exe_sections[nsections - 1].chr & 0x80000000)) { uint32_t rsize, vsize, dam = 0; vsize = exe_sections[nsections - 1].uvsz; rsize = exe_sections[nsections - 1].rsz; if(rsize < exe_sections[nsections - 1].ursz) { rsize = exe_sections[nsections - 1].ursz; dam = 1; } if(vsize >= 0x612c && rsize >= 0x612c && ((vsize & 0xff) == 0xec)) { int bw = rsize < 0x7000 ? rsize : 0x7000; const char *tbuff; if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) { if(cli_memstr(tbuff, 4091, \"\\xe8\\x2c\\x61\\x00\\x00\", 5)) { cli_append_virus(ctx, dam ? \"Heuristics.W32.Magistr.A.dam\" : \"Heuristics.W32.Magistr.A\"); if (!SCAN_ALL) { free(exe_sections); return CL_VIRUS; } viruses_found++; } } } else if(rsize >= 0x7000 && vsize >= 0x7000 && ((vsize & 0xff) == 0xed)) { int bw = rsize < 0x8000 ? rsize : 0x8000; const char *tbuff; if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) { if(cli_memstr(tbuff, 4091, \"\\xe8\\x04\\x72\\x00\\x00\", 5)) { cli_append_virus(ctx,dam ? \"Heuristics.W32.Magistr.B.dam\" : \"Heuristics.W32.Magistr.B\"); if (!SCAN_ALL) { free(exe_sections); return CL_VIRUS; } viruses_found++; } } } } \/* W32.Polipos.A *\/ while(polipos && !dll && nsections > 2 && nsections < 13 && e_lfanew <= 0x800 && (EC16(optional_hdr32.Subsystem) == 2 || EC16(optional_hdr32.Subsystem) == 3) && EC16(file_hdr.Machine) == 0x14c && optional_hdr32.SizeOfStackReserve >= 0x80000) { uint32_t jump, jold, *jumps = NULL; const uint8_t *code; unsigned int xsjs = 0; if(exe_sections[0].rsz > CLI_MAX_ALLOCATION) break; if(!exe_sections[0].rsz) break; if(!(code=fmap_need_off_once(map, exe_sections[0].raw, exe_sections[0].rsz))) break; for(i=0; i 1) continue; jump = cli_rawaddr(exe_sections[0].rva+i+5+cli_readint32(&code[i+1]), exe_sections, nsections, &err, fsize, hdr_size); if(err || !CLI_ISCONTAINED(exe_sections[polipos].raw, exe_sections[polipos].rsz, jump, 9)) continue; if(xsjs % 128 == 0) { if(xsjs == 1280) break; if(!(jumps=(uint32_t *)cli_realloc2(jumps, (xsjs+128)*sizeof(uint32_t)))) { free(exe_sections); return CL_EMEM; } } j=0; for(; j 1 && fsize > 64*1024 && fsize < 4*1024*1024) { if(dirs[2].Size) { struct swizz_stats *stats = cli_calloc(1, sizeof(*stats)); unsigned int m = 1000; ret = CL_CLEAN; if (!stats) ret = CL_EMEM; else { cli_parseres_special(EC32(dirs[2].VirtualAddress), EC32(dirs[2].VirtualAddress), map, exe_sections, nsections, fsize, hdr_size, 0, 0, &m, stats); if ((ret = cli_detect_swizz(stats)) == CL_VIRUS) { cli_append_virus(ctx,\"Heuristics.Trojan.Swizzor.Gen\"); } free(stats); } if (ret != CL_CLEAN) { if (!(ret == CL_VIRUS && SCAN_ALL)) { free(exe_sections); return ret; } viruses_found++; } } } \/* !!!!!!!!!!!!!! PACKERS START HERE !!!!!!!!!!!!!! *\/ corrupted_cur = ctx->corrupted_input; ctx->corrupted_input = 2; \/* caller will reset on return *\/ \/* UPX, FSG, MEW support *\/ \/* try to find the first section with physical size == 0 *\/ found = 0; if(DCONF & (PE_CONF_UPX | PE_CONF_FSG | PE_CONF_MEW)) { for(i = 0; i < (unsigned int) nsections - 1; i++) { if(!exe_sections[i].rsz && exe_sections[i].vsz && exe_sections[i + 1].rsz && exe_sections[i + 1].vsz) { found = 1; cli_dbgmsg(\"UPX\/FSG\/MEW: empty section found - assuming compression\\n\"); #if HAVE_JSON cli_jsonbool(pe_json, \"HasEmptySection\", 1); #endif break; } } } \/* MEW support *\/ if (found && (DCONF & PE_CONF_MEW) && epsize>=16 && epbuff[0]=='\\xe9') { uint32_t fileoffset; const char *tbuff; fileoffset = (vep + cli_readint32(epbuff + 1) + 5); while (fileoffset == 0x154 || fileoffset == 0x158) { char *src; uint32_t offdiff, uselzma; cli_dbgmsg (\"MEW: found MEW characteristics %08X + %08X + 5 = %08X\\n\", cli_readint32(epbuff + 1), vep, cli_readint32(epbuff + 1) + vep + 5); if(!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0))) break; if (fileoffset == 0x154) cli_dbgmsg(\"MEW: Win9x compatibility was set!\\n\"); else cli_dbgmsg(\"MEW: Win9x compatibility was NOT set!\\n\"); if((offdiff = cli_readint32(tbuff+1) - EC32(optional_hdr32.ImageBase)) <= exe_sections[i + 1].rva || offdiff >= exe_sections[i + 1].rva + exe_sections[i + 1].raw - 4) { cli_dbgmsg(\"MEW: ESI is not in proper section\\n\"); break; } offdiff -= exe_sections[i + 1].rva; if(!exe_sections[i + 1].rsz) { cli_dbgmsg(\"MEW: mew section is empty\\n\"); break; } ssize = exe_sections[i + 1].vsz; dsize = exe_sections[i].vsz; cli_dbgmsg(\"MEW: ssize %08x dsize %08x offdiff: %08x\\n\", ssize, dsize, offdiff); CLI_UNPSIZELIMITS(\"MEW\", MAX(ssize, dsize)); CLI_UNPSIZELIMITS(\"MEW\", MAX(ssize + dsize, exe_sections[i + 1].rsz)); if (exe_sections[i + 1].rsz < offdiff + 12 || exe_sections[i + 1].rsz > ssize) { cli_dbgmsg(\"MEW: Size mismatch: %08x\\n\", exe_sections[i + 1].rsz); break; } \/* allocate needed buffer *\/ if (!(src = cli_calloc (ssize + dsize, sizeof(char)))) { free(exe_sections); return CL_EMEM; } if((bytes = fmap_readn(map, src + dsize, exe_sections[i + 1].raw, exe_sections[i + 1].rsz)) != exe_sections[i + 1].rsz) { cli_dbgmsg(\"MEW: Can't read %d bytes [read: %lu]\\n\", exe_sections[i + 1].rsz, (unsigned long)bytes); free(exe_sections); free(src); return CL_EREAD; } cli_dbgmsg(\"MEW: %u (%08x) bytes read\\n\", (unsigned int)bytes, (unsigned int)bytes); \/* count offset to lzma proc, if lzma used, 0xe8 -> call *\/ if (tbuff[0x7b] == '\\xe8') { if (!CLI_ISCONTAINED(exe_sections[1].rva, exe_sections[1].vsz, cli_readint32(tbuff + 0x7c) + fileoffset + 0x80, 4)) { cli_dbgmsg(\"MEW: lzma proc out of bounds!\\n\"); free(src); break; \/* to next unpacker in chain *\/ } uselzma = cli_readint32(tbuff + 0x7c) - (exe_sections[0].rva - fileoffset - 0x80); } else { uselzma = 0; } #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"MEW\"); #endif CLI_UNPTEMP(\"MEW\",(src,exe_sections,0)); CLI_UNPRESULTS(\"MEW\",(unmew11(src, offdiff, ssize, dsize, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, uselzma, ndesc)),1,(src,0)); break; } } if(epsize<168) { free(exe_sections); return CL_CLEAN; } if (found || upack) { \/* Check EP for UPX vs. FSG vs. Upack *\/ \/* Upack 0.39 produces 2 types of executables * 3 sections: | 2 sections (one empty, I don't chech found if !upack, since it's in OR above): * mov esi, value | pusha * lodsd | call $+0x9 * push eax | * * Upack 1.1\/1.2 Beta produces [based on 2 samples (sUx) provided by aCaB]: * 2 sections * mov esi, value * loads * mov edi, eax * * Upack unknown [sample 0297729] * 3 sections * mov esi, value * push [esi] * jmp * *\/ \/* upack 0.39-3s + sample 0151477*\/ while(((upack && nsections == 3) && \/* 3 sections *\/ (( epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && \/* mov esi *\/ epbuff[5] == '\\xad' && epbuff[6] == '\\x50' \/* lodsd; push eax *\/ ) || \/* based on 0297729 sample from aCaB *\/ (epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && \/* mov esi *\/ epbuff[5] == '\\xff' && epbuff[6] == '\\x36' \/* push [esi] *\/ ) )) || ((!upack && nsections == 2) && \/* 2 sections *\/ (( \/* upack 0.39-2s *\/ epbuff[0] == '\\x60' && epbuff[1] == '\\xe8' && cli_readint32(epbuff+2) == 0x9 \/* pusha; call+9 *\/ ) || ( \/* upack 1.1\/1.2, based on 2 samples *\/ epbuff[0] == '\\xbe' && cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase) < min && \/* mov esi *\/ cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > 0 && epbuff[5] == '\\xad' && epbuff[6] == '\\x8b' && epbuff[7] == '\\xf8' \/* loads; mov edi, eax *\/ ) )) ) { uint32_t vma, off; int a,b,c; cli_dbgmsg(\"Upack characteristics found.\\n\"); a = exe_sections[0].vsz; b = exe_sections[1].vsz; if (upack) { cli_dbgmsg(\"Upack: var set\\n\"); c = exe_sections[2].vsz; ssize = exe_sections[0].ursz + exe_sections[0].uraw; off = exe_sections[0].rva; vma = EC32(optional_hdr32.ImageBase) + exe_sections[0].rva; } else { cli_dbgmsg(\"Upack: var NOT set\\n\"); c = exe_sections[1].rva; ssize = exe_sections[1].uraw; off = 0; vma = exe_sections[1].rva - exe_sections[1].uraw; } dsize = a+b+c; CLI_UNPSIZELIMITS(\"Upack\", MAX(MAX(dsize, ssize), exe_sections[1].ursz)); if (!CLI_ISCONTAINED(0, dsize, exe_sections[1].rva - off, exe_sections[1].ursz) || (upack && !CLI_ISCONTAINED(0, dsize, exe_sections[2].rva - exe_sections[0].rva, ssize)) || ssize > dsize) { cli_dbgmsg(\"Upack: probably malformed pe-header, skipping to next unpacker\\n\"); break; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); return CL_EMEM; } if((unsigned int)fmap_readn(map, dest, 0, ssize) != ssize) { cli_dbgmsg(\"Upack: Can't read raw data of section 0\\n\"); free(dest); break; } if(upack) memmove(dest + exe_sections[2].rva - exe_sections[0].rva, dest, ssize); if((unsigned int)fmap_readn(map, dest + exe_sections[1].rva - off, exe_sections[1].uraw, exe_sections[1].ursz) != exe_sections[1].ursz) { cli_dbgmsg(\"Upack: Can't read raw data of section 1\\n\"); free(dest); break; } #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"Upack\"); #endif CLI_UNPTEMP(\"Upack\",(dest,exe_sections,0)); CLI_UNPRESULTS(\"Upack\",(unupack(upack, dest, dsize, epbuff, vma, ep, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, ndesc)),1,(dest,0)); break; } } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\x87' && epbuff[1] == '\\x25') { const char *dst; \/* FSG v2.0 support - thanks to aCaB ! *\/ uint32_t newesi, newedi, newebx, newedx; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; CLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } newedx = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase); if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) { cli_dbgmsg(\"FSG: xchg out of bounds (%x), giving up\\n\", newedx); break; } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"Can't read raw data of section %d\\n\", i + 1); free(exe_sections); return CL_ESEEK; } dst = src + newedx - exe_sections[i + 1].rva; if(newedx < exe_sections[i + 1].rva || !CLI_ISCONTAINED(src, ssize, dst, 4)) { cli_dbgmsg(\"FSG: New ESP out of bounds\\n\"); break; } newedx = cli_readint32(dst) - EC32(optional_hdr32.ImageBase); if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) { cli_dbgmsg(\"FSG: New ESP (%x) is wrong\\n\", newedx); break; } dst = src + newedx - exe_sections[i + 1].rva; if(!CLI_ISCONTAINED(src, ssize, dst, 32)) { cli_dbgmsg(\"FSG: New stack out of bounds\\n\"); break; } newedi = cli_readint32(dst) - EC32(optional_hdr32.ImageBase); newesi = cli_readint32(dst + 4) - EC32(optional_hdr32.ImageBase); newebx = cli_readint32(dst + 16) - EC32(optional_hdr32.ImageBase); newedx = cli_readint32(dst + 20); if(newedi != exe_sections[i].rva) { cli_dbgmsg(\"FSG: Bad destination buffer (edi is %x should be %x)\\n\", newedi, exe_sections[i].rva); break; } if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) { cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\"); break; } if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newebx, 16)) { cli_dbgmsg(\"FSG: Array of functions out of bounds\\n\"); break; } newedx=cli_readint32(newebx + 12 - exe_sections[i + 1].rva + src) - EC32(optional_hdr32.ImageBase); cli_dbgmsg(\"FSG: found old EP @%x\\n\",newedx); if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); return CL_EMEM; } #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"FSG\"); #endif CLI_UNPTEMP(\"FSG\",(dest,exe_sections,0)); CLI_UNPRESULTSFSG2(\"FSG\",(unfsg_200(newesi - exe_sections[i + 1].rva + src, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, newedi, EC32(optional_hdr32.ImageBase), newedx, ndesc)),1,(dest,0)); break; } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min) { \/* FSG support - v. 1.33 (thx trog for the many samples) *\/ int sectcnt = 0; const char *support; uint32_t newesi, newedi, oldep, gp, t; struct cli_exe_section *sections; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; CLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } if(!(t = cli_rawaddr(cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size)) && err ) { cli_dbgmsg(\"FSG: Support data out of padding area\\n\"); break; } gp = exe_sections[i + 1].raw - t; CLI_UNPSIZELIMITS(\"FSG\", gp); if(!(support = fmap_need_off_once(map, t, gp))) { cli_dbgmsg(\"Can't read %d bytes from padding area\\n\", gp); free(exe_sections); return CL_EREAD; } \/* newebx = cli_readint32(support) - EC32(optional_hdr32.ImageBase); Unused *\/ newedi = cli_readint32(support + 4) - EC32(optional_hdr32.ImageBase); \/* 1st dest *\/ newesi = cli_readint32(support + 8) - EC32(optional_hdr32.ImageBase); \/* Source *\/ if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) { cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\"); break; } if(newedi != exe_sections[i].rva) { cli_dbgmsg(\"FSG: Bad destination (is %x should be %x)\\n\", newedi, exe_sections[i].rva); break; } \/* Counting original sections *\/ for(t = 12; t < gp - 4; t += 4) { uint32_t rva = cli_readint32(support+t); if(!rva) break; rva -= EC32(optional_hdr32.ImageBase)+1; sectcnt++; if(rva % 0x1000) cli_dbgmsg(\"FSG: Original section %d is misaligned\\n\", sectcnt); if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) { cli_dbgmsg(\"FSG: Original section %d is out of bounds\\n\", sectcnt); break; } } if(t >= gp - 4 || cli_readint32(support + t)) { break; } if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { cli_errmsg(\"FSG: Unable to allocate memory for sections %lu\\n\", (sectcnt + 1) * sizeof(struct cli_exe_section)); free(exe_sections); return CL_EMEM; } sections[0].rva = newedi; for(t = 1; t <= (uint32_t)sectcnt; t++) sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(optional_hdr32.ImageBase); if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"Can't read raw data of section %d\\n\", i); free(exe_sections); free(sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(sections); return CL_EMEM; } oldep = vep + 161 + 6 + cli_readint32(epbuff+163); cli_dbgmsg(\"FSG: found old EP @%x\\n\", oldep); #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"FSG\"); #endif CLI_UNPTEMP(\"FSG\",(dest,sections,exe_sections,0)); CLI_UNPRESULTSFSG1(\"FSG\",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0)); break; \/* were done with 1.33 *\/ } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\xbb' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min && epbuff[5] == '\\xbf' && epbuff[10] == '\\xbe' && vep >= exe_sections[i + 1].rva && vep - exe_sections[i + 1].rva > exe_sections[i + 1].rva - 0xe0 ) { \/* FSG support - v. 1.31 *\/ int sectcnt = 0; uint32_t gp, t = cli_rawaddr(cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size); const char *support; uint32_t newesi = cli_readint32(epbuff+11) - EC32(optional_hdr32.ImageBase); uint32_t newedi = cli_readint32(epbuff+6) - EC32(optional_hdr32.ImageBase); uint32_t oldep = vep - exe_sections[i + 1].rva; struct cli_exe_section *sections; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; if(err) { cli_dbgmsg(\"FSG: Support data out of padding area\\n\"); break; } if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].raw) { cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\"); break; } if(newedi != exe_sections[i].rva) { cli_dbgmsg(\"FSG: Bad destination (is %x should be %x)\\n\", newedi, exe_sections[i].rva); break; } CLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } gp = exe_sections[i + 1].raw - t; CLI_UNPSIZELIMITS(\"FSG\", gp) if(!(support = fmap_need_off_once(map, t, gp))) { cli_dbgmsg(\"Can't read %d bytes from padding area\\n\", gp); free(exe_sections); return CL_EREAD; } \/* Counting original sections *\/ for(t = 0; t < gp - 2; t += 2) { uint32_t rva = support[t]|(support[t+1]<<8); if (rva == 2 || rva == 1) break; rva = ((rva-2)<<12) - EC32(optional_hdr32.ImageBase); sectcnt++; if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) { cli_dbgmsg(\"FSG: Original section %d is out of bounds\\n\", sectcnt); break; } } if(t >= gp-10 || cli_readint32(support + t + 6) != 2) { break; } if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { cli_errmsg(\"FSG: Unable to allocate memory for sections %lu\\n\", (sectcnt + 1) * sizeof(struct cli_exe_section)); free(exe_sections); return CL_EMEM; } sections[0].rva = newedi; for(t = 0; t <= (uint32_t)sectcnt - 1; t++) { sections[t+1].rva = (((support[t*2]|(support[t*2+1]<<8))-2)<<12)-EC32(optional_hdr32.ImageBase); } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"FSG: Can't read raw data of section %d\\n\", i); free(exe_sections); free(sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(sections); return CL_EMEM; } gp = 0xda + 6*(epbuff[16]=='\\xe8'); oldep = vep + gp + 6 + cli_readint32(src+gp+2+oldep); cli_dbgmsg(\"FSG: found old EP @%x\\n\", oldep); #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"FSG\"); #endif CLI_UNPTEMP(\"FSG\",(dest,sections,exe_sections,0)); CLI_UNPRESULTSFSG1(\"FSG\",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0)); break; \/* were done with 1.31 *\/ } if(found && (DCONF & PE_CONF_UPX)) { \/* UPX support *\/ \/* we assume (i + 1) is UPX1 *\/ ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz + exe_sections[i + 1].vsz; \/* cli_dbgmsg(\"UPX: ssize %u dsize %u\\n\", ssize, dsize); *\/ CLI_UNPSIZELIMITS(\"UPX\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize || dsize > CLI_MAX_ALLOCATION ) { cli_dbgmsg(\"UPX: Size mismatch or dsize too big (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"UPX: Can't read raw data of section %d\\n\", i+1); free(exe_sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize + 8192, sizeof(char))) == NULL) { free(exe_sections); return CL_EMEM; } \/* try to detect UPX code *\/ if(cli_memstr(UPX_NRV2B, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2B, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg(\"UPX: Looks like a NRV2B decompression routine\\n\"); upxfn = upx_inflate2b; } else if(cli_memstr(UPX_NRV2D, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2D, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg(\"UPX: Looks like a NRV2D decompression routine\\n\"); upxfn = upx_inflate2d; } else if(cli_memstr(UPX_NRV2E, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2E, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg(\"UPX: Looks like a NRV2E decompression routine\\n\"); upxfn = upx_inflate2e; } if(upxfn) { int skew = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase) - exe_sections[i + 1].rva; if(epbuff[1] != '\\xbe' || skew <= 0 || skew > 0xfff) { \/* FIXME: legit skews?? *\/ skew = 0; } else if ((unsigned int)skew > ssize) { \/* Ignore suggested skew larger than section size *\/ skew = 0; } else { cli_dbgmsg(\"UPX: UPX1 seems skewed by %d bytes\\n\", skew); } \/* Try skewed first (skew may be zero) *\/ if(upxfn(src + skew, ssize - skew, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep-skew) >= 0) { upx_success = 1; } \/* If skew not successful and non-zero, try no skew *\/ else if(skew && (upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)) { upx_success = 1; } if(upx_success) cli_dbgmsg(\"UPX: Successfully decompressed\\n\"); else cli_dbgmsg(\"UPX: Preferred decompressor failed\\n\"); } if(!upx_success && upxfn != upx_inflate2b) { if(upx_inflate2b(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2b(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg(\"UPX: NRV2B decompressor failed\\n\"); } else { upx_success = 1; cli_dbgmsg(\"UPX: Successfully decompressed with NRV2B\\n\"); } } if(!upx_success && upxfn != upx_inflate2d) { if(upx_inflate2d(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2d(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg(\"UPX: NRV2D decompressor failed\\n\"); } else { upx_success = 1; cli_dbgmsg(\"UPX: Successfully decompressed with NRV2D\\n\"); } } if(!upx_success && upxfn != upx_inflate2e) { if(upx_inflate2e(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2e(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg(\"UPX: NRV2E decompressor failed\\n\"); } else { upx_success = 1; cli_dbgmsg(\"UPX: Successfully decompressed with NRV2E\\n\"); } } if(cli_memstr(UPX_LZMA2, 20, epbuff + 0x2f, 20)) { uint32_t strictdsize=cli_readint32(epbuff+0x21), skew = 0; if(ssize > 0x15 && epbuff[0] == '\\x60' && epbuff[1] == '\\xbe') { skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase; if(skew!=0x15) skew = 0; } if(strictdsize<=dsize) upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0; } else if (cli_memstr(UPX_LZMA1, 20, epbuff + 0x39, 20)) { uint32_t strictdsize=cli_readint32(epbuff+0x2b), skew = 0; if(ssize > 0x15 && epbuff[0] == '\\x60' && epbuff[1] == '\\xbe') { skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase; if(skew!=0x15) skew = 0; } if(strictdsize<=dsize) upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0; } if(!upx_success) { cli_dbgmsg(\"UPX: All decompressors failed\\n\"); free(dest); } } if(upx_success) { free(exe_sections); CLI_UNPTEMP(\"UPX\/FSG\",(dest,0)); #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"UPX\"); #endif if((unsigned int) write(ndesc, dest, dsize) != dsize) { cli_dbgmsg(\"UPX\/FSG: Can't write %d bytes\\n\", dsize); free(tempfile); free(dest); close(ndesc); return CL_EWRITE; } free(dest); if (lseek(ndesc, 0, SEEK_SET) == -1) { cli_dbgmsg(\"UPX\/FSG: lseek() failed\\n\"); close(ndesc); CLI_TMPUNLK(); free(tempfile); SHA_RESET; return CL_ESEEK; } if(ctx->engine->keeptmp) cli_dbgmsg(\"UPX\/FSG: Decompressed data saved in %s\\n\", tempfile); cli_dbgmsg(\"***** Scanning decompressed file *****\\n\"); SHA_OFF; if((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS) { close(ndesc); CLI_TMPUNLK(); free(tempfile); SHA_RESET; return CL_VIRUS; } SHA_RESET; close(ndesc); CLI_TMPUNLK(); free(tempfile); return ret; } \/* Petite *\/ if(epsize<200) { free(exe_sections); return CL_CLEAN; } found = 2; if(epbuff[0] != '\\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 1].rva + EC32(optional_hdr32.ImageBase)) { if(nsections < 2 || epbuff[0] != '\\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 2].rva + EC32(optional_hdr32.ImageBase)) found = 0; else found = 1; } if(found && (DCONF & PE_CONF_PETITE)) { cli_dbgmsg(\"Petite: v2.%d compression detected\\n\", found); if(cli_readint32(epbuff + 0x80) == 0x163c988d) { cli_dbgmsg(\"Petite: level zero compression is not supported yet\\n\"); } else { dsize = max - min; CLI_UNPSIZELIMITS(\"Petite\", dsize); if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { cli_dbgmsg(\"Petite: Can't allocate %d bytes\\n\", dsize); free(exe_sections); return CL_EMEM; } for(i = 0 ; i < nsections; i++) { if(exe_sections[i].raw) { if(!exe_sections[i].rsz || (unsigned int)fmap_readn(map, dest + exe_sections[i].rva - min, exe_sections[i].raw, exe_sections[i].ursz) != exe_sections[i].ursz) { free(exe_sections); free(dest); return CL_CLEAN; } } } #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"Petite\"); #endif CLI_UNPTEMP(\"Petite\",(dest,exe_sections,0)); CLI_UNPRESULTS(\"Petite\",(petite_inflate2x_1to9(dest, min, max - min, exe_sections, nsections - (found == 1 ? 1 : 0), EC32(optional_hdr32.ImageBase),vep, ndesc, found, EC32(optional_hdr32.DataDirectory[2].VirtualAddress),EC32(optional_hdr32.DataDirectory[2].Size))),0,(dest,0)); } } \/* PESpin 1.1 *\/ if((DCONF & PE_CONF_PESPIN) && nsections > 1 && vep >= exe_sections[nsections - 1].rva && vep < exe_sections[nsections - 1].rva + exe_sections[nsections - 1].rsz - 0x3217 - 4 && memcmp(epbuff+4, \"\\xe8\\x00\\x00\\x00\\x00\\x8b\\x1c\\x24\\x83\\xc3\", 10) == 0) { char *spinned; CLI_UNPSIZELIMITS(\"PEspin\", fsize); if((spinned = (char *) cli_malloc(fsize)) == NULL) { cli_errmsg(\"PESping: Unable to allocate memory for spinned %lu\\n\", (unsigned long)fsize); free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) { cli_dbgmsg(\"PESpin: Can't read %lu bytes\\n\", (unsigned long)fsize); free(spinned); free(exe_sections); return CL_EREAD; } #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"PEspin\"); #endif CLI_UNPTEMP(\"PESpin\",(spinned,exe_sections,0)); CLI_UNPRESULTS_(\"PEspin\",SPINCASE(),(unspin(spinned, fsize, exe_sections, nsections - 1, vep, ndesc, ctx)),0,(spinned,0)); } \/* yC 1.3 & variants *\/ if((DCONF & PE_CONF_YC) && nsections > 1 && (EC32(optional_hdr32.AddressOfEntryPoint) == exe_sections[nsections - 1].rva + 0x60)) { uint32_t ecx = 0; int16_t offset; \/* yC 1.3 *\/ if (!memcmp(epbuff, \"\\x55\\x8B\\xEC\\x53\\x56\\x57\\x60\\xE8\\x00\\x00\\x00\\x00\\x5D\\x81\\xED\", 15) && !memcmp(epbuff+0x26, \"\\x8D\\x3A\\x8B\\xF7\\x33\\xC0\\xEB\\x04\\x90\\xEB\\x01\\xC2\\xAC\", 13) && ((uint8_t)epbuff[0x13] == 0xB9) && ((uint16_t)(cli_readint16(epbuff+0x18)) == 0xE981) && !memcmp(epbuff+0x1e,\"\\x8B\\xD5\\x81\\xC2\", 4)) { offset = 0; if (0x6c - cli_readint32(epbuff+0xf) + cli_readint32(epbuff+0x22) == 0xC6) ecx = cli_readint32(epbuff+0x14) - cli_readint32(epbuff+0x1a); } \/* yC 1.3 variant *\/ if (!ecx && !memcmp(epbuff, \"\\x55\\x8B\\xEC\\x83\\xEC\\x40\\x53\\x56\\x57\", 9) && !memcmp(epbuff+0x17, \"\\xe8\\x00\\x00\\x00\\x00\\x5d\\x81\\xed\", 8) && ((uint8_t)epbuff[0x23] == 0xB9)) { offset = 0x10; if (0x6c - cli_readint32(epbuff+0x1f) + cli_readint32(epbuff+0x32) == 0xC6) ecx = cli_readint32(epbuff+0x24) - cli_readint32(epbuff+0x2a); } \/* yC 1.x\/modified *\/ if (!ecx && !memcmp(epbuff, \"\\x60\\xe8\\x00\\x00\\x00\\x00\\x5d\\x81\\xed\",9) && ((uint8_t)epbuff[0xd] == 0xb9) && ((uint16_t)cli_readint16(epbuff + 0x12)== 0xbd8d) && !memcmp(epbuff+0x18, \"\\x8b\\xf7\\xac\", 3)) { offset = -0x18; if (0x66 - cli_readint32(epbuff+0x9) + cli_readint32(epbuff+0x14) == 0xae) ecx = cli_readint32(epbuff+0xe); } if (ecx > 0x800 && ecx < 0x2000 && !memcmp(epbuff+0x63+offset, \"\\xaa\\xe2\\xcc\", 3) && (fsize >= exe_sections[nsections-1].raw + 0xC6 + ecx + offset)) { char *spinned; if((spinned = (char *) cli_malloc(fsize)) == NULL) { cli_errmsg(\"yC: Unable to allocate memory for spinned %lu\\n\", (unsigned long)fsize); free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) { cli_dbgmsg(\"yC: Can't read %lu bytes\\n\", (unsigned long)fsize); free(spinned); free(exe_sections); return CL_EREAD; } #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"yC\"); #endif cli_dbgmsg(\"%d,%d,%d,%d\\n\", nsections-1, e_lfanew, ecx, offset); CLI_UNPTEMP(\"yC\",(spinned,exe_sections,0)); CLI_UNPRESULTS(\"yC\",(yc_decrypt(spinned, fsize, exe_sections, nsections-1, e_lfanew, ndesc, ecx, offset)),0,(spinned,0)); } } \/* WWPack *\/ while ((DCONF & PE_CONF_WWPACK) && nsections > 1 && vep == exe_sections[nsections - 1].rva && memcmp(epbuff, \"\\x53\\x55\\x8b\\xe8\\x33\\xdb\\xeb\", 7) == 0 && memcmp(epbuff+0x68, \"\\xe8\\x00\\x00\\x00\\x00\\x58\\x2d\\x6d\\x00\\x00\\x00\\x50\\x60\\x33\\xc9\\x50\\x58\\x50\\x50\", 19) == 0) { uint32_t head = exe_sections[nsections - 1].raw; uint8_t *packer; char *src; ssize = 0; for(i=0 ; ; i++) { if(exe_sections[i].rawssize) break; CLI_UNPSIZELIMITS(\"WWPack\", ssize); if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, src, 0, head) != head) { cli_dbgmsg(\"WWPack: Can't read %d bytes from headers\\n\", head); free(src); free(exe_sections); return CL_EREAD; } for(i = 0 ; i < (unsigned int)nsections-1; i++) { if(!exe_sections[i].rsz) continue; if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break; if((unsigned int)fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break; } if(i+1!=nsections) { cli_dbgmsg(\"WWpack: Probably hacked\/damaged file.\\n\"); free(src); break; } if((packer = (uint8_t *) cli_calloc(exe_sections[nsections - 1].rsz, sizeof(char))) == NULL) { free(src); free(exe_sections); return CL_EMEM; } if(!exe_sections[nsections - 1].rsz || (size_t) fmap_readn(map, packer, exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz) != exe_sections[nsections - 1].rsz) { cli_dbgmsg(\"WWPack: Can't read %d bytes from wwpack sect\\n\", exe_sections[nsections - 1].rsz); free(src); free(packer); free(exe_sections); return CL_EREAD; } #if HAVE_JSON cli_jsonstr(pe_json, \"Packer\", \"WWPack\"); #endif CLI_UNPTEMP(\"WWPack\",(src,packer,exe_sections,0)); CLI_UNPRESULTS(\"WWPack\",(wwunpack((uint8_t *)src, ssize, packer, exe_sections, nsections-1, e_lfanew, ndesc)),0,(src,packer,0)); break; } \/* ASPACK support *\/ while((DCONF & PE_CONF_ASPACK) && ep+58+0x70e < fsize && !memcmp(epbuff,\"\\x60\\xe8\\x03\\x00\\x00\\x00\\xe9\\xeb\",8)) { char *src; if(epsize<0x3bf || memcmp(epbuff+0x3b9, \"\\x68\\x00\\x00\\x00\\x00\\xc3\",6)) break; ssize = 0; for(i=0 ; i< nsections ; i++) if(ssizecorrupted_input = corrupted_cur; \/* Bytecode BC_PE_UNPACKER hook *\/ bc_ctx = cli_bytecode_context_alloc(); if (!bc_ctx) { cli_errmsg(\"cli_scanpe: can't allocate memory for bc_ctx\\n\"); return CL_EMEM; } cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections); cli_bytecode_context_setctx(bc_ctx, ctx); ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_UNPACKER, map); switch (ret) { case CL_VIRUS: free(exe_sections); cli_bytecode_context_destroy(bc_ctx); return CL_VIRUS; case CL_SUCCESS: ndesc = cli_bytecode_context_getresult_file(bc_ctx, &tempfile); cli_bytecode_context_destroy(bc_ctx); if (ndesc != -1 && tempfile) { CLI_UNPRESULTS(\"bytecode PE hook\", 1, 1, (0)); } break; default: cli_bytecode_context_destroy(bc_ctx); } free(exe_sections); #if HAVE_JSON if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) { return CL_ETIMEOUT; } #endif if (SCAN_ALL && viruses_found) return CL_VIRUS; return CL_CLEAN;","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":217184,"input":"unsigned CjfifDecode::DecodeMarker() { TCHAR acIdentifier[MAX_IDENTIFIER]; CString strTmp; CString strFull; \/\/ Used for concatenation unsigned nLength; \/\/ General purpose unsigned nTmpVal; unsigned nCode; unsigned long nPosEnd; unsigned long nPosSaved; \/\/ General-purpose saved position in file unsigned long nPosExifStart; unsigned nRet; \/\/ General purpose return value bool bRet; unsigned long nPosMarkerStart; \/\/ Offset for current marker unsigned nColTransform = 0; \/\/ Color Transform from APP14 marker \/\/ For DQT CString strDqtPrecision = _T(\"\"); CString strDqtZigZagOrder = _T(\"\"); if (Buf(m_nPos) != 0xFF) { if (m_nPos == 0) { \/\/ Don't give error message if we've already alerted them of AVI \/ PSD if ((!m_bAvi) && (!m_bPsd)) { strTmp.Format(_T(\"NOTE: File did not start with JPEG marker. Consider using [Tools->Img Search Fwd] to locate embedded JPEG.\")); m_pLog->AddLineErr(strTmp); } } else { strTmp.Format(_T(\"ERROR: Expected marker 0xFF, got 0x%02X @ offset 0x%08X. Consider using [Tools->Img Search Fwd\/Rev].\"),Buf(m_nPos),m_nPos); m_pLog->AddLineErr(strTmp); } m_nPos++; return DECMARK_ERR; } m_nPos++; \/\/ Read the current marker code nCode = Buf(m_nPos++); \/\/ Handle Marker Padding \/\/ \/\/ According to Section B.1.1.2: \/\/ \"Any marker may optionally be preceded by any number of fill bytes, which are bytes assigned code XFF.\" \/\/ unsigned nSkipMarkerPad = 0; while (nCode == 0xFF) { \/\/ Count the pad nSkipMarkerPad++; \/\/ Read another byte nCode = Buf(m_nPos++); } \/\/ Report out any padding if (nSkipMarkerPad>0) { strTmp.Format(_T(\"*** Skipped %u marker pad bytes ***\"),nSkipMarkerPad); m_pLog->AddLineHdr(strTmp); } \/\/ Save the current marker offset nPosMarkerStart = m_nPos; AddHeader(nCode); switch (nCode) { case JFIF_SOI: \/\/ SOI m_bStateSoi = true; break; case JFIF_APP12: \/\/ Photoshop DUCKY (Save For Web) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; \/\/ Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T(\"Ducky\")) != 0) { m_pLog->AddLine(_T(\" Not Photoshop DUCKY. Skipping remainder.\")); } else \/\/ Photoshop { \/\/ Please see reference on http:\/\/cpan.uwinnipeg.ca\/htdocs\/Image-ExifTool\/Image\/ExifTool\/APP12.pm.html \/\/ A direct indexed approach should be safe m_nImgQualPhotoshopSfw = Buf(m_nPos+6); strTmp.Format(_T(\" Photoshop Save For Web Quality = [%d]\"),m_nImgQualPhotoshopSfw); m_pLog->AddLine(strTmp); } \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP14: \/\/ JPEG Adobe tag nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; \/\/ Some files had very short segment (eg. nLength=2) if (nLength < 2+12) { m_pLog->AddLine(_T(\" Segment too short for Identifier. Skipping remainder.\")); m_nPos = nPosSaved+nLength; break; } m_nPos += 2; \/\/ Move past length now that we've used it \/\/ TODO: Confirm Adobe flag m_nPos += 5; nTmpVal = Buf(m_nPos+0)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" DCTEncodeVersion = %u\"),nTmpVal); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3); strTmp.Format(_T(\" APP14Flags0 = %u\"),nTmpVal); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos+4)*256 + Buf(m_nPos+5); strTmp.Format(_T(\" APP14Flags1 = %u\"),nTmpVal); m_pLog->AddLine(strTmp); nColTransform = Buf(m_nPos+6); switch (nColTransform) { case APP14_COLXFM_UNK_RGB: strTmp.Format(_T(\" ColorTransform = %u [Unknown (RGB or CMYK)]\"),nColTransform); break; case APP14_COLXFM_YCC: strTmp.Format(_T(\" ColorTransform = %u [YCbCr]\"),nColTransform); break; case APP14_COLXFM_YCCK: strTmp.Format(_T(\" ColorTransform = %u [YCCK]\"),nColTransform); break; default: strTmp.Format(_T(\" ColorTransform = %u [???]\"),nColTransform); break; } m_pLog->AddLine(strTmp); m_nApp14ColTransform = (nColTransform & 0xFF); \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP13: \/\/ Photoshop (Save As) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; \/\/ Some files had very short segment (eg. nLength=2) if (nLength < 2+20) { m_pLog->AddLine(_T(\" Segment too short for Identifier. Skipping remainder.\")); m_nPos = nPosSaved+nLength; break; } m_nPos += 2; \/\/ Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T(\"Photoshop 3.0\")) != 0) { m_pLog->AddLine(_T(\" Not Photoshop. Skipping remainder.\")); } else \/\/ Photoshop { DecodeApp13Ps(); } \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP1: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; \/\/ Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier); if (!_tcsnccmp(acIdentifier,_T(\"http:\/\/ns.adobe.com\/xap\/1.0\/\\x00\"),29) != 0) { \/\/ XMP m_pLog->AddLine(_T(\" XMP = \")); m_nPos++; unsigned nPosMarkerEnd = nPosSaved+nLength-1; unsigned sXmpLen = nPosMarkerEnd-m_nPos; char cXmpChar; bool bNonSpace; CString strLine; \/\/ Reset state strLine = _T(\" |\"); bNonSpace = false; for (unsigned nInd=0;nIndBuf(m_nPos+nInd); \/\/ Detect a non-space in line if ((cXmpChar != 0x20) && (cXmpChar != 0x0A)) { bNonSpace = true; } \/\/ Detect Linefeed, print out line if (cXmpChar == 0x0A) { \/\/ Only print line if some non-space elements! if (bNonSpace) { m_pLog->AddLine(strLine); } \/\/ Reset state strLine = _T(\" |\"); bNonSpace = false; } else { \/\/ Add the char strLine.AppendChar(cXmpChar); } } } else if (!_tcscmp(acIdentifier,_T(\"Exif\")) != 0) { \/\/ Only decode it further if it is EXIF format m_nPos += 2; \/\/ Skip two 00 bytes nPosExifStart = m_nPos; \/\/ Save m_nPos @ start of EXIF used for all IFD offsets \/\/ =========== EXIF TIFF Header (Start) =========== \/\/ - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.5.2 \/\/ - Contents (8 bytes total) \/\/ - Byte order (2 bytes) \/\/ - 0x002A (2 bytes) \/\/ - Offset of 0th IFD (4 bytes) unsigned char acIdentifierTiff[9]; strFull = _T(\"\"); strTmp = _T(\"\"); strFull = _T(\" Identifier TIFF = \"); for (unsigned int i=0;i<8;i++) { acIdentifierTiff[i] = (unsigned char)Buf(m_nPos++); } strTmp = PrintAsHexUC(acIdentifierTiff,8); strFull += strTmp; m_pLog->AddLine(strFull); switch (acIdentifierTiff[0]*256+acIdentifierTiff[1]) { case 0x4949: \/\/ \"II\" \/\/ Intel alignment m_nImgExifEndian = 0; m_pLog->AddLine(_T(\" Endian = Intel (little)\")); break; case 0x4D4D: \/\/ \"MM\" \/\/ Motorola alignment m_nImgExifEndian = 1; m_pLog->AddLine(_T(\" Endian = Motorola (big)\")); break; } \/\/ We expect the TAG mark of 0x002A (depending on endian mode) unsigned test_002a; test_002a = ByteSwap2(acIdentifierTiff[2],acIdentifierTiff[3]); strTmp.Format(_T(\" TAG Mark x002A = 0x%04X\"),test_002a); m_pLog->AddLine(strTmp); unsigned nIfdCount; \/\/ Current IFD # unsigned nOffsetIfd1; \/\/ Mark pointer to EXIF Sub IFD as 0 so that we can \/\/ detect if the tag never showed up. m_nImgExifSubIfdPtr = 0; m_nImgExifMakerPtr = 0; m_nImgExifGpsIfdPtr = 0; m_nImgExifInteropIfdPtr = 0; bool exif_done = FALSE; nOffsetIfd1 = ByteSwap4(acIdentifierTiff[4],acIdentifierTiff[5], acIdentifierTiff[6],acIdentifierTiff[7]); \/\/ =========== EXIF TIFF Header (End) =========== \/\/ =========== EXIF IFD 0 =========== \/\/ Do we start the 0th IFD for the \"Primary Image Data\"? \/\/ Even though the nOffsetIfd1 pointer should indicate to \/\/ us where the IFD should start (0x0008 if immediately after \/\/ EXIF TIFF Header), I have observed JPEG files that \/\/ do not contain the IFD. Therefore, we must check for this \/\/ condition by comparing against the APP marker length. \/\/ Example file: http:\/\/img9.imageshack.us\/img9\/194\/90114543.jpg if ((nPosSaved + nLength) <= (nPosExifStart+nOffsetIfd1)) { \/\/ We've run out of space for any IFD, so cancel now exif_done = true; m_pLog->AddLine(_T(\" NOTE: No IFD entries\")); } nIfdCount = 0; while (!exif_done) { m_pLog->AddLine(_T(\"\")); strTmp.Format(_T(\"IFD%u\"),nIfdCount); \/\/ Process the IFD nRet = DecodeExifIfd(strTmp,nPosExifStart,nOffsetIfd1); \/\/ Now that we have gone through all entries in the IFD directory, \/\/ we read the offset to the next IFD nOffsetIfd1 = ByteSwap4(Buf(m_nPos+0),Buf(m_nPos+1),Buf(m_nPos+2),Buf(m_nPos+3)); m_nPos += 4; strTmp.Format(_T(\" Offset to Next IFD = 0x%08X\"),nOffsetIfd1); m_pLog->AddLine(strTmp); if (nRet != 0) { \/\/ Error condition (DecodeExifIfd returned error) nOffsetIfd1 = 0x00000000; } if (nOffsetIfd1 == 0x00000000) { \/\/ Either error condition or truly end of IFDs exif_done = TRUE; } else { nIfdCount++; } } \/\/ while ! exif_done \/\/ If EXIF SubIFD was defined, then handle it now if (m_nImgExifSubIfdPtr != 0) { m_pLog->AddLine(_T(\"\")); DecodeExifIfd(_T(\"SubIFD\"),nPosExifStart,m_nImgExifSubIfdPtr); } if (m_nImgExifMakerPtr != 0) { m_pLog->AddLine(_T(\"\")); DecodeExifIfd(_T(\"MakerIFD\"),nPosExifStart,m_nImgExifMakerPtr); } if (m_nImgExifGpsIfdPtr != 0) { m_pLog->AddLine(_T(\"\")); DecodeExifIfd(_T(\"GPSIFD\"),nPosExifStart,m_nImgExifGpsIfdPtr); } if (m_nImgExifInteropIfdPtr != 0) { m_pLog->AddLine(_T(\"\")); DecodeExifIfd(_T(\"InteropIFD\"),nPosExifStart,m_nImgExifInteropIfdPtr); } } else { strTmp.Format(_T(\"Identifier [%s] not supported. Skipping remainder.\"),(LPCTSTR)acIdentifier); m_pLog->AddLine(strTmp); } \/\/\/\/\/\/\/\/\/\/ \/\/ Dump out Makernote area \/\/ TODO: Disabled for now #if 0 unsigned ptr_base; if (m_bVerbose) { if (m_nImgExifMakerPtr != 0) { \/\/ FIXME: Seems that nPosExifStart is not initialized in VERBOSE mode ptr_base = nPosExifStart+m_nImgExifMakerPtr; m_pLog->AddLine(_T(\"Exif Maker IFD DUMP\")); strFull.Format(_T(\" MarkerOffset @ 0x%08X\"),ptr_base); m_pLog->AddLine(strFull); } } #endif \/\/ End of dump out makernote area \/\/ Restore file position m_nPos = nPosSaved; \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP2: \/\/ Typically used for Flashpix and possibly ICC profiles \/\/ Photoshop (Save As) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nPosSaved = m_nPos; m_nPos += 2; \/\/ Move past length now that we've used it _tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); acIdentifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),acIdentifier); m_pLog->AddLine(strTmp); m_nPos += (unsigned)_tcslen(acIdentifier)+1; if (_tcscmp(acIdentifier,_T(\"FPXR\")) == 0) { \/\/ Photoshop m_pLog->AddLine(_T(\" FlashPix:\")); DecodeApp2Flashpix(); } else if (_tcscmp(acIdentifier,_T(\"ICC_PROFILE\")) == 0) { \/\/ ICC Profile m_pLog->AddLine(_T(\" ICC Profile:\")); DecodeApp2IccProfile(nLength); } else { m_pLog->AddLine(_T(\" Not supported. Skipping remainder.\")); } \/\/ Restore original position in file to a point \/\/ after the section m_nPos = nPosSaved+nLength; break; case JFIF_APP3: case JFIF_APP4: case JFIF_APP5: case JFIF_APP6: case JFIF_APP7: case JFIF_APP8: case JFIF_APP9: case JFIF_APP10: case JFIF_APP11: \/\/case JFIF_APP12: \/\/ Handled separately \/\/case JFIF_APP13: \/\/ Handled separately \/\/case JFIF_APP14: \/\/ Handled separately case JFIF_APP15: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); if (m_bVerbose) { strFull = _T(\"\"); for (unsigned int i=0;iAddLine(strFull); strFull = _T(\"\"); } } m_pLog->AddLine(strFull); strFull = _T(\"\"); for (unsigned int i=0;iAddLine(strFull); } } m_pLog->AddLine(strFull); } \/\/ nVerbose m_nPos += nLength; break; case JFIF_APP0: \/\/ APP0 nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); _tcscpy_s(m_acApp0Identifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1)); m_acApp0Identifier[MAX_IDENTIFIER-1] = 0; \/\/ Null terminate just in case strTmp.Format(_T(\" Identifier = [%s]\"),m_acApp0Identifier); m_pLog->AddLine(strTmp); if (!_tcscmp(m_acApp0Identifier,_T(\"JFIF\"))) { \/\/ Only process remainder if it is JFIF. This marker \/\/ is also used for application-specific functions. m_nPos += (unsigned)(_tcslen(m_acApp0Identifier)+1); m_nImgVersionMajor = Buf(m_nPos++); m_nImgVersionMinor = Buf(m_nPos++); strTmp.Format(_T(\" version = [%u.%u]\"),m_nImgVersionMajor,m_nImgVersionMinor); m_pLog->AddLine(strTmp); m_nImgUnits = Buf(m_nPos++); m_nImgDensityX = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/m_nImgDensityX = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; m_nImgDensityY = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/m_nImgDensityY = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian); m_nPos+=2; strTmp.Format(_T(\" density = %u x %u \"),m_nImgDensityX,m_nImgDensityY); strFull = strTmp; switch (m_nImgUnits) { case 0: strFull += _T(\"(aspect ratio)\"); m_pLog->AddLine(strFull); break; case 1: strFull += _T(\"DPI (dots per inch)\"); m_pLog->AddLine(strFull); break; case 2: strFull += _T(\"DPcm (dots per cm)\"); m_pLog->AddLine(strFull); break; default: strTmp.Format(_T(\"ERROR: Unknown ImgUnits parameter [%u]\"),m_nImgUnits); strFull += strTmp; m_pLog->AddLineWarn(strFull); \/\/return DECMARK_ERR; break; } m_nImgThumbSizeX = Buf(m_nPos++); m_nImgThumbSizeY = Buf(m_nPos++); strTmp.Format(_T(\" thumbnail = %u x %u\"),m_nImgThumbSizeX,m_nImgThumbSizeY); m_pLog->AddLine(strTmp); \/\/ Unpack the thumbnail: unsigned thumbnail_r,thumbnail_g,thumbnail_b; if (m_nImgThumbSizeX && m_nImgThumbSizeY) { for (unsigned y=0;yAddLine(strFull); } } } \/\/ TODO: \/\/ - In JPEG-B mode (GeoRaster), we will need to fake out \/\/ the DHT & DQT tables here. Unfortunately, we'll have to \/\/ rely on the user to put us into this mode as there is nothing \/\/ in the file that specifies this mode. \/* \/\/ TODO: Need to ensure that Faked DHT is correct table AddHeader(JFIF_DHT_FAKE); DecodeDHT(true); \/\/ Need to mark DHT tables as OK m_bStateDht = true; m_bStateDhtFake = true; m_bStateDhtOk = true; \/\/ ... same for DQT *\/ } else if (!_tcsnccmp(m_acApp0Identifier,_T(\"AVI1\"),4)) { \/\/ AVI MJPEG type \/\/ Need to fill in predefined DHT table from spec: \/\/ OpenDML file format for AVI, section \"Proposed Data Chunk Format\" \/\/ Described in MMREG.H m_pLog->AddLine(_T(\" Detected MotionJPEG\")); m_pLog->AddLine(_T(\" Importing standard Huffman table...\")); m_pLog->AddLine(_T(\"\")); AddHeader(JFIF_DHT_FAKE); DecodeDHT(true); \/\/ Need to mark DHT tables as OK m_bStateDht = true; m_bStateDhtFake = true; m_bStateDhtOk = true; m_nPos += nLength-2; \/\/ Skip over, and undo length short read } else { \/\/ Not JFIF or AVI1 m_pLog->AddLine(_T(\" Not known APP0 type. Skipping remainder.\")); m_nPos += nLength-2; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DQT: \/\/ Define quantization tables m_bStateDqt = true; unsigned nDqtPrecision_Pq; unsigned nDqtQuantDestId_Tq; nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Lq nPosEnd = m_nPos+nLength; m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Table length = %u\"),nLength); strTmp.Format(_T(\" Table length = %u\"),nLength); m_pLog->AddLine(strTmp); while (nPosEnd > m_nPos) { strTmp.Format(_T(\" ----\")); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos++); \/\/ Pq | Tq nDqtPrecision_Pq = (nTmpVal & 0xF0) >> 4; \/\/ Pq, range 0-1 nDqtQuantDestId_Tq = nTmpVal & 0x0F; \/\/ Tq, range 0-3 \/\/ Decode per ITU-T.81 standard #if 1 if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T(\"8 bits\"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T(\"16 bits\"); } else { strTmp.Format(_T(\" Unsupported precision value [%u]\"),nDqtPrecision_Pq); m_pLog->AddLineWarn(strTmp); strDqtPrecision = _T(\"???\"); \/\/ FIXME: Consider terminating marker parsing early } if (!ValidateValue(nDqtPrecision_Pq,0,1,_T(\"DQT Precision \"),true,0)) return DECMARK_ERR; if (!ValidateValue(nDqtQuantDestId_Tq,0,3,_T(\"DQT Destination ID \"),true,0)) return DECMARK_ERR; strTmp.Format(_T(\" Precision=%s\"),(LPCTSTR)strDqtPrecision); m_pLog->AddLine(strTmp); #else \/\/ Decode with additional DQT extension (ITU-T-JPEG-Plus-Proposal_R3.doc) if ((nDqtPrecision_Pq & 0xE) == 0) { \/\/ Per ITU-T.81 Standard if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T(\"8 bits\"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T(\"16 bits\"); } strTmp.Format(_T(\" Precision=%s\"),strDqtPrecision); m_pLog->AddLine(strTmp); } else { \/\/ Non-standard \/\/ JPEG-Plus-Proposal-R3: \/\/ - Alternative sub-block-wise sequence strTmp.Format(_T(\" Non-Standard DQT Extension detected\")); m_pLog->AddLineWarn(strTmp); \/\/ FIXME: Should prevent attempt to decode until this is implemented if (nDqtPrecision_Pq == 0) { strDqtPrecision = _T(\"8 bits\"); } else if (nDqtPrecision_Pq == 1) { strDqtPrecision = _T(\"16 bits\"); } strTmp.Format(_T(\" Precision=%s\"),strDqtPrecision); m_pLog->AddLine(strTmp); if ((nDqtPrecision_Pq & 0x2) == 0) { strDqtZigZagOrder = _T(\"Diagonal zig-zag coeff scan seqeunce\"); } else if ((nDqtPrecision_Pq & 0x2) == 1) { strDqtZigZagOrder = _T(\"Alternate coeff scan seqeunce\"); } strTmp.Format(_T(\" Coeff Scan Sequence=%s\"),strDqtZigZagOrder); m_pLog->AddLine(strTmp); if ((nDqtPrecision_Pq & 0x4) == 1) { strTmp.Format(_T(\" Custom coeff scan sequence\")); m_pLog->AddLine(strTmp); \/\/ Now expect sequence of 64 coefficient entries CString strSequence = _T(\"\"); for (unsigned nInd=0;nInd<64;nInd++) { nTmpVal = Buf(m_nPos++); strTmp.Format(_T(\"%u\"),nTmpVal); strSequence += strTmp; if (nInd!=63) { strSequence += _T(\", \"); } } strTmp.Format(_T(\" Custom sequence = [ %s ]\"),strSequence); m_pLog->AddLine(strTmp); } } #endif strTmp.Format(_T(\" Destination ID=%u\"),nDqtQuantDestId_Tq); if (nDqtQuantDestId_Tq == 0) { strTmp += _T(\" (Luminance)\"); } else if (nDqtQuantDestId_Tq == 1) { strTmp += _T(\" (Chrominance)\"); } else if (nDqtQuantDestId_Tq == 2) { strTmp += _T(\" (Chrominance)\"); } else { strTmp += _T(\" (???)\"); } m_pLog->AddLine(strTmp); \/\/ FIXME: The following is somewhat superseded by ValidateValue() above \/\/ with the exception of skipping remainder if (nDqtQuantDestId_Tq >= MAX_DQT_DEST_ID) { strTmp.Format(_T(\"ERROR: Destination ID = %u, >= %u\"),nDqtQuantDestId_Tq,MAX_DQT_DEST_ID); m_pLog->AddLineErr(strTmp); if (!m_pAppConfig->bRelaxedParsing) { m_pLog->AddLineErr(_T(\" Stopping decode\")); return DECMARK_ERR; } else { \/\/ Now skip remainder of DQT \/\/ FIXME strTmp.Format(_T(\" Skipping remainder of marker [%u bytes]\"),nPosMarkerStart + nLength - m_nPos); m_pLog->AddLineWarn(strTmp); m_pLog->AddLine(_T(\"\")); m_nPos = nPosMarkerStart + nLength; return DECMARK_OK; } } bool bQuantAllOnes = true; double dComparePercent; double dSumPercent=0; double dSumPercentSqr=0; for (unsigned nCoeffInd=0;nCoeffInd low freq \/\/ To X,Y, left-to-right, top-to-bottom \/\/ Flag this DQT table as being set! m_abImgDqtSet[nDqtQuantDestId_Tq] = true; unsigned nCoeffInd; \/\/ Now display the table for (unsigned nDqtY=0;nDqtY<8;nDqtY++) { strFull.Format(_T(\" DQT, Row #%u: \"),nDqtY); for (unsigned nDqtX=0;nDqtX<8;nDqtX++) { nCoeffInd = nDqtY*8+nDqtX; strTmp.Format(_T(\"%3u \"),m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]); strFull += strTmp; \/\/ Store the DQT entry into the Image Decoder bRet = m_pImgDec->SetDqtEntry(nDqtQuantDestId_Tq,nCoeffInd,glb_anUnZigZag[nCoeffInd], m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]); DecodeErrCheck(bRet); } \/\/ Now add the compare with Annex K \/\/ Decided to disable this as it was confusing users \/* strFull += _T(\" AnnexRatio: <\"); for (unsigned nDqtX=0;nDqtX<8;nDqtX++) { nCoeffInd = nDqtY*8+nDqtX; if (nDqtQuantDestId_Tq == 0) { strTmp.Format(_T(\"%5.1f \"),m_afStdQuantLumCompare[nCoeffInd]); } else { strTmp.Format(_T(\"%5.1f \"),m_afStdQuantChrCompare[nCoeffInd]); } strFull += strTmp; } strFull += _T(\">\"); *\/ m_pLog->AddLine(strFull); } \/\/ Perform some statistical analysis of the quality factor \/\/ to determine the likelihood of the current quantization \/\/ table being a scaled version of the \"standard\" tables. \/\/ If the variance is high, it is unlikely to be the case. double dQuality; double dVariance; dSumPercent \/= 64.0; \/* mean scale factor *\/ dSumPercentSqr \/= 64.0; dVariance = dSumPercentSqr - (dSumPercent * dSumPercent); \/* variance *\/ \/\/ Generate the equivalent IJQ \"quality\" factor if (bQuantAllOnes) \/* special case for all-ones table *\/ dQuality = 100.0; else if (dSumPercent <= 100.0) dQuality = (200.0 - dSumPercent) \/ 2.0; else dQuality = 5000.0 \/ dSumPercent; \/\/ Save the quality rating for later m_adImgDqtQual[nDqtQuantDestId_Tq] = dQuality; strTmp.Format(_T(\" Approx quality factor = %.2f (scaling=%.2f variance=%.2f)\"), dQuality,dSumPercent,dVariance); m_pLog->AddLine(strTmp); } m_bStateDqtOk = true; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DAC: \/\/ DAC (Arithmetic Coding) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ La m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Arithmetic coding header length = %u\"),nLength); strTmp.Format(_T(\" Arithmetic coding header length = %u\"),nLength); m_pLog->AddLine(strTmp); unsigned nDAC_n; unsigned nDAC_Tc,nDAC_Tb; unsigned nDAC_Cs; nDAC_n = (nLength>2)?(nLength-2)\/2:0; for (unsigned nInd=0;nInd> 4; nDAC_Tb = (nTmpVal & 0x0F); \/\/XXX strTmp.Format(_T(\" #%02u: Table class = %u\"),nInd+1,nDAC_Tc); strTmp.Format(_T(\" #%02u: Table class = %u\"),nInd+1,nDAC_Tc); m_pLog->AddLine(strTmp); \/\/XXX strTmp.Format(_T(\" #%02u: Table destination identifier = %u\"),nInd+1,nDAC_Tb); strTmp.Format(_T(\" #%02u: Table destination identifier = %u\"),nInd+1,nDAC_Tb); m_pLog->AddLine(strTmp); nDAC_Cs = Buf(m_nPos++); \/\/ Cs \/\/XXX strTmp.Format(_T(\" #%02u: Conditioning table value = %u\"),nInd+1,nDAC_Cs); strTmp.Format(_T(\" #%02u: Conditioning table value = %u\"),nInd+1,nDAC_Cs); m_pLog->AddLine(strTmp); if (!ValidateValue(nDAC_Tc,0,1,_T(\"Table class \"),true,0)) return DECMARK_ERR; if (!ValidateValue(nDAC_Tb,0,3,_T(\"Table destination ID \"),true,0)) return DECMARK_ERR; \/\/ Parameter range constraints per Table B.6: \/\/ ------------|-------------------------|-------------------|------------ \/\/ | Sequential DCT | Progressive DCT | Lossless \/\/ Parameter | Baseline Extended | | \/\/ ------------|-----------|-------------|-------------------|------------ \/\/ Cs | Undef | Tc=0: 0-255 | Tc=0: 0-255 | 0-255 \/\/ | | Tc=1: 1-63 | Tc=1: 1-63 | \/\/ ------------|-----------|-------------|-------------------|------------ \/\/ However, to keep it simple (and not depend on lossless mode), \/\/ we will only check the maximal range if (!ValidateValue(nDAC_Cs,0,255,_T(\"Conditioning table value \"),true,0)) return DECMARK_ERR; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_DNL: \/\/ DNL (Define number of lines) nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Ld m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Header length = %u\"),nLength); strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ NL m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Number of lines = %u\"),nTmpVal); strTmp.Format(_T(\" Number of lines = %u\"),nTmpVal); m_pLog->AddLine(strTmp); if (!ValidateValue(nTmpVal,1,65535,_T(\"Number of lines \"),true,1)) return DECMARK_ERR; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_EXP: nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Le m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Header length = %u\"),nLength); strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); unsigned nEXP_Eh,nEXP_Ev; nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Eh,Ev nEXP_Eh = (nTmpVal & 0xF0) >> 4; nEXP_Ev = (nTmpVal & 0x0F); m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Expand horizontally = %u\"),nEXP_Eh); strTmp.Format(_T(\" Expand horizontally = %u\"),nEXP_Eh); m_pLog->AddLine(strTmp); \/\/XXX strTmp.Format(_T(\" Expand vertically = %u\"),nEXP_Ev); strTmp.Format(_T(\" Expand vertically = %u\"),nEXP_Ev); m_pLog->AddLine(strTmp); if (!ValidateValue(nEXP_Eh,0,1,_T(\"Expand horizontally \"),true,0)) return DECMARK_ERR; if (!ValidateValue(nEXP_Ev,0,1,_T(\"Expand vertically \"),true,0)) return DECMARK_ERR; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_SOF0: \/\/ SOF0 (Baseline DCT) case JFIF_SOF1: \/\/ SOF1 (Extended sequential) case JFIF_SOF2: \/\/ SOF2 (Progressive) case JFIF_SOF3: case JFIF_SOF5: case JFIF_SOF6: case JFIF_SOF7: case JFIF_SOF9: case JFIF_SOF10: case JFIF_SOF11: case JFIF_SOF13: case JFIF_SOF14: case JFIF_SOF15: \/\/ TODO: \/\/ - JFIF_DHP should be able to reuse the JFIF_SOF marker parsing \/\/ however as we don't support hierarchical image decode, we \/\/ would want to skip the update of class members. m_bStateSof = true; \/\/ Determine if this is a SOF mode that we support \/\/ At this time, we only support Baseline DCT & Extended Sequential Baseline DCT \/\/ (non-differential) with Huffman coding. Progressive, Lossless, \/\/ Differential and Arithmetic coded modes are not supported. m_bImgSofUnsupported = true; if (nCode == JFIF_SOF0) { m_bImgSofUnsupported = false; } if (nCode == JFIF_SOF1) { m_bImgSofUnsupported = false; } \/\/ For reference, note progressive scan files even though \/\/ we don't currently support their decode if (nCode == JFIF_SOF2) { m_bImgProgressive = true; } nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Lf m_nPos+=2; \/\/XXX strTmp.Format(_T(\" Frame header length = %u\"),nLength); strTmp.Format(_T(\" Frame header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_nSofPrecision_P = Buf(m_nPos++); \/\/ P \/\/XXX strTmp.Format(_T(\" Precision

= %u\"),m_nSofPrecision_P); strTmp.Format(_T(\" Precision = %u\"),m_nSofPrecision_P); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofPrecision_P,2,16,_T(\"Precision

\"),true,8)) return DECMARK_ERR; m_nSofNumLines_Y = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Y m_nPos += 2; \/\/XXX strTmp.Format(_T(\" Number of Lines = %u\"),m_nSofNumLines_Y); strTmp.Format(_T(\" Number of Lines = %u\"),m_nSofNumLines_Y); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofNumLines_Y,0,65535,_T(\"Number of Lines \"),true,0)) return DECMARK_ERR; m_nSofSampsPerLine_X = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ X m_nPos += 2; \/\/XXX strTmp.Format(_T(\" Samples per Line = %u\"),m_nSofSampsPerLine_X); strTmp.Format(_T(\" Samples per Line = %u\"),m_nSofSampsPerLine_X); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofSampsPerLine_X,1,65535,_T(\"Samples per Line \"),true,1)) return DECMARK_ERR; strTmp.Format(_T(\" Image Size = %u x %u\"),m_nSofSampsPerLine_X,m_nSofNumLines_Y); m_pLog->AddLine(strTmp); \/\/ Determine orientation \/\/ m_nSofSampsPerLine_X = X \/\/ m_nSofNumLines_Y = Y m_eImgLandscape = ENUM_LANDSCAPE_YES; if (m_nSofNumLines_Y > m_nSofSampsPerLine_X) m_eImgLandscape = ENUM_LANDSCAPE_NO; strTmp.Format(_T(\" Raw Image Orientation = %s\"),(m_eImgLandscape==ENUM_LANDSCAPE_YES)?_T(\"Landscape\"):_T(\"Portrait\")); m_pLog->AddLine(strTmp); m_nSofNumComps_Nf = Buf(m_nPos++); \/\/ Nf, range 1..255 \/\/XXX strTmp.Format(_T(\" Number of Img components = %u\"),m_nSofNumComps_Nf); strTmp.Format(_T(\" Number of Img components = %u\"),m_nSofNumComps_Nf); m_pLog->AddLine(strTmp); if (!ValidateValue(m_nSofNumComps_Nf,1,255,_T(\"Number of Img components \"),true,1)) return DECMARK_ERR; unsigned nCompIdent; unsigned anSofSampFact[MAX_SOF_COMP_NF]; m_nSofHorzSampFactMax_Hmax = 0; m_nSofVertSampFactMax_Vmax = 0; \/\/ Now clear the output image content (all components) \/\/ TODO: Migrate some of the bitmap allocation \/ clearing from \/\/ DecodeScanImg() into ResetImageContent() and call here \/\/m_pImgDec->ResetImageContent(); \/\/ Per JFIF v1.02: \/\/ - Nf = 1 or 3 \/\/ - C1 = Y \/\/ - C2 = Cb \/\/ - C3 = Cr for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = Buf(m_nPos++); \/\/ Ci, range 0..255 m_anSofQuantCompId[nCompInd] = nCompIdent; \/\/if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T(\"Component ID \"),true,0)) return DECMARK_ERR; anSofSampFact[nCompIdent] = Buf(m_nPos++); m_anSofQuantTblSel_Tqi[nCompIdent] = Buf(m_nPos++); \/\/ Tqi, range 0..3 \/\/if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T(\"Table Destination ID \"),true,0)) return DECMARK_ERR; \/\/ NOTE: We protect against bad input here as replication ratios are \/\/ determined later that depend on dividing by sampling factor (hence \/\/ possibility of div by 0). m_anSofHorzSampFact_Hi[nCompIdent] = (anSofSampFact[nCompIdent] & 0xF0) >> 4; \/\/ Hi, range 1..4 m_anSofVertSampFact_Vi[nCompIdent] = (anSofSampFact[nCompIdent] & 0x0F); \/\/ Vi, range 1..4 \/\/if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T(\"Horizontal Sampling Factor \"),true,1)) return DECMARK_ERR; \/\/if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T(\"Vertical Sampling Factor \"),true,1)) return DECMARK_ERR; } \/\/ Calculate max sampling factors for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; \/\/ Calculate maximum sampling factor for the SOF. This is only \/\/ used for later generation of m_strImgQuantCss an the SOF \/\/ reporting below. The CimgDecode block is responsible for \/\/ calculating the maximum sampling factor on a per-scan basis. m_nSofHorzSampFactMax_Hmax = max(m_nSofHorzSampFactMax_Hmax,m_anSofHorzSampFact_Hi[nCompIdent]); m_nSofVertSampFactMax_Vmax = max(m_nSofVertSampFactMax_Vmax,m_anSofVertSampFact_Vi[nCompIdent]); } \/\/ Report per-component sampling factors and quantization table selectors for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; \/\/ Create subsampling ratio \/\/ - Protect against division-by-zero CString strSubsampH = _T(\"?\"); CString strSubsampV = _T(\"?\"); if (m_anSofHorzSampFact_Hi[nCompIdent] > 0) { strSubsampH.Format(_T(\"%u\"),m_nSofHorzSampFactMax_Hmax\/m_anSofHorzSampFact_Hi[nCompIdent]); } if (m_anSofVertSampFact_Vi[nCompIdent] > 0) { strSubsampV.Format(_T(\"%u\"),m_nSofVertSampFactMax_Vmax\/m_anSofVertSampFact_Vi[nCompIdent]); } strFull.Format(_T(\" Component[%u]: \"),nCompInd); \/\/ Note i in Ci is 1-based \/\/XXX strTmp.Format(_T(\"ID=0x%02X, Samp Fac =0x%02X (Subsamp %u x %u), Quant Tbl Sel =0x%02X\"), strTmp.Format(_T(\"ID=0x%02X, Samp Fac=0x%02X (Subsamp %s x %s), Quant Tbl Sel=0x%02X\"), nCompIdent,anSofSampFact[nCompIdent], (LPCTSTR)strSubsampH,(LPCTSTR)strSubsampV, m_anSofQuantTblSel_Tqi[nCompIdent]); strFull += strTmp; \/\/ Mapping from component index (not ID) to colour channel per JFIF if (m_nSofNumComps_Nf == 1) { \/\/ Assume grayscale strFull += _T(\" (Lum: Y)\"); } else if (m_nSofNumComps_Nf == 3) { \/\/ Assume YCC if (nCompInd == SCAN_COMP_Y) { strFull += _T(\" (Lum: Y)\"); } else if (nCompInd == SCAN_COMP_CB) { strFull += _T(\" (Chrom: Cb)\"); } else if (nCompInd == SCAN_COMP_CR) { strFull += _T(\" (Chrom: Cr)\"); } } else if (m_nSofNumComps_Nf == 4) { \/\/ Assume YCCK if (nCompInd == 1) { strFull += _T(\" (Y)\"); } else if (nCompInd == 2) { strFull += _T(\" (Cb)\"); } else if (nCompInd == 3) { strFull += _T(\" (Cr)\"); } else if (nCompInd == 4) { strFull += _T(\" (K)\"); } } else { strFull += _T(\" (???)\"); \/\/ Unknown } m_pLog->AddLine(strFull); } \/\/ Test for bad input, clean up if bad for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T(\"Component ID \"),true,0)) return DECMARK_ERR; if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T(\"Table Destination ID \"),true,0)) return DECMARK_ERR; if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T(\"Horizontal Sampling Factor \"),true,1)) return DECMARK_ERR; if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T(\"Vertical Sampling Factor \"),true,1)) return DECMARK_ERR; } \/\/ Finally, assign the cleaned values to the decoder for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++) { nCompIdent = m_anSofQuantCompId[nCompInd]; \/\/ Store the DQT Table selection for the Image Decoder \/\/ Param values: Nf,Tqi \/\/ Param ranges: 1..255,0..3 \/\/ Note that the Image Decoder doesn't need to see the Component Identifiers bRet = m_pImgDec->SetDqtTables(nCompInd,m_anSofQuantTblSel_Tqi[nCompIdent]); DecodeErrCheck(bRet); \/\/ Store the Precision (to handle 12-bit decode) m_pImgDec->SetPrecision(m_nSofPrecision_P); } if (!m_bStateAbort) { \/\/ Set the component sampling factors (chroma subsampling) \/\/ FIXME: check ranging for (unsigned nCompInd=1;nCompInd<=m_nSofNumComps_Nf;nCompInd++) { \/\/ nCompInd is component index (1...Nf) \/\/ nCompIdent is Component Identifier (Ci) \/\/ Note that the Image Decoder doesn't need to see the Component Identifiers nCompIdent = m_anSofQuantCompId[nCompInd]; m_pImgDec->SetSofSampFactors(nCompInd,m_anSofHorzSampFact_Hi[nCompIdent],m_anSofVertSampFact_Vi[nCompIdent]); } \/\/ Now mark the image as been somewhat OK (ie. should \/\/ also be suitable for EmbeddedThumb() and PrepareSignature() m_bImgOK = true; m_bStateSofOk = true; } if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_COM: \/\/ COM nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); m_nPos+=2; strTmp.Format(_T(\" Comment length = %u\"),nLength); m_pLog->AddLine(strTmp); \/\/ Check for JPEG COM vulnerability \/\/ http:\/\/marc.info\/?l=bugtraq&m=109524346729948 \/\/ Note that the recovery is not very graceful. It will assume that the \/\/ field is actually zero-length, which will make the next byte trigger the \/\/ \"Expected marker 0xFF\" error message and probably abort. There is no \/\/ obvious way to if ( (nLength == 0) || (nLength == 1) ) { strTmp.Format(_T(\" JPEG Comment Field Vulnerability detected!\")); m_pLog->AddLineErr(strTmp); strTmp.Format(_T(\" Skipping data until next marker...\")); m_pLog->AddLineErr(strTmp); nLength = 2; bool bDoneSearch = false; unsigned nSkipStart = m_nPos; while (!bDoneSearch) { if (Buf(m_nPos) != 0xFF) { m_nPos++; } else { bDoneSearch = true; } if (m_nPos >= m_pWBuf->GetPosEof()) { bDoneSearch = true; } } strTmp.Format(_T(\" Skipped %u bytes\"),m_nPos - nSkipStart); m_pLog->AddLineErr(strTmp); \/\/ Break out of case statement break; } \/\/ Assume COM field valid length (ie. >= 2) strFull = _T(\" Comment=\"); m_strComment = _T(\"\"); for (unsigned ind=0;indAddLine(strFull); break; case JFIF_DHT: \/\/ DHT m_bStateDht = true; DecodeDHT(false); m_bStateDhtOk = true; break; case JFIF_SOS: \/\/ SOS unsigned long nPosScanStart; \/\/ Byte count at start of scan data segment m_bStateSos = true; \/\/ NOTE: Only want to capture position of first SOS \/\/ This should make other function such as AVI frame extract \/\/ more robust in case we get multiple SOS segments. \/\/ We assume that this value is reset when we start a new decode if (m_nPosSos == 0) { m_nPosSos = m_nPos-2; \/\/ Used for Extract. Want to include actual marker } nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); m_nPos+=2; \/\/ Ensure that we have seen proper markers before we try this one! if (!m_bStateSofOk) { strTmp.Format(_T(\" ERROR: SOS before valid SOF defined\")); m_pLog->AddLineErr(strTmp); return DECMARK_ERR; } strTmp.Format(_T(\" Scan header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_nSosNumCompScan_Ns = Buf(m_nPos++); \/\/ Ns, range 1..4 \/\/XXX strTmp.Format(_T(\" Number of image components = %u\"),m_nSosNumCompScan_Ns); strTmp.Format(_T(\" Number of img components = %u\"),m_nSosNumCompScan_Ns); m_pLog->AddLine(strTmp); \/\/ Just in case something got corrupted, don't want to get out \/\/ of range here. Note that this will be a hard abort, and \/\/ will not resume decoding. if (m_nSosNumCompScan_Ns > MAX_SOS_COMP_NS) { strTmp.Format(_T(\" ERROR: Scan decode does not support > %u components\"),MAX_SOS_COMP_NS); m_pLog->AddLineErr(strTmp); return DECMARK_ERR; } unsigned nSosCompSel_Cs; unsigned nSosHuffTblSel; unsigned nSosHuffTblSelDc_Td; unsigned nSosHuffTblSelAc_Ta; \/\/ Max range of components indices is between 1..4 for (unsigned int nScanCompInd=1;((nScanCompInd<=m_nSosNumCompScan_Ns) && (!m_bStateAbort));nScanCompInd++) { strFull.Format(_T(\" Component[%u]: \"),nScanCompInd); nSosCompSel_Cs = Buf(m_nPos++); \/\/ Cs, range 0..255 nSosHuffTblSel = Buf(m_nPos++); nSosHuffTblSelDc_Td = (nSosHuffTblSel & 0xf0)>>4; \/\/ Td, range 0..3 nSosHuffTblSelAc_Ta = (nSosHuffTblSel & 0x0f); \/\/ Ta, range 0..3 strTmp.Format(_T(\"selector=0x%02X, table=%u(DC),%u(AC)\"),nSosCompSel_Cs,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta); strFull += strTmp; m_pLog->AddLine(strFull); bRet = m_pImgDec->SetDhtTables(nScanCompInd,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta); DecodeErrCheck(bRet); } m_nSosSpectralStart_Ss = Buf(m_nPos++); m_nSosSpectralEnd_Se = Buf(m_nPos++); m_nSosSuccApprox_A = Buf(m_nPos++); strTmp.Format(_T(\" Spectral selection = %u .. %u\"),m_nSosSpectralStart_Ss,m_nSosSpectralEnd_Se); m_pLog->AddLine(strTmp); strTmp.Format(_T(\" Successive approximation = 0x%02X\"),m_nSosSuccApprox_A); m_pLog->AddLine(strTmp); if (m_pAppConfig->bOutputScanDump) { m_pLog->AddLine(_T(\"\")); m_pLog->AddLine(_T(\" Scan Data: (after bitstuff removed)\")); } \/\/ Save the scan data segment position nPosScanStart = m_nPos; \/\/ Skip over the Scan Data segment \/\/ Pass 1) Quick, allowing for bOutputScanDump to dump first 640B. \/\/ Pass 2) If bDecodeScanImg, we redo the process but in detail decoding. \/\/ FIXME: Not sure why, but if I skip over Pass 1 (eg if I leave in the \/\/ following line uncommented), then I get an error at the end of the \/\/ pass 2 decode (indicating that EOI marker not seen, and expecting \/\/ marker). \/\/ if (m_pAppConfig->bOutputScanDump) { \/\/ --- PASS 1 --- bool bSkipDone; unsigned nSkipCount; unsigned nSkipData; unsigned nSkipPos; bool bScanDumpTrunc; bSkipDone = false; nSkipCount = 0; nSkipPos = 0; bScanDumpTrunc = FALSE; strFull = _T(\"\"); while (!bSkipDone) { nSkipCount++; nSkipPos++; nSkipData = Buf(m_nPos++); if (nSkipData == 0xFF) { \/\/ this could either be a marker or a byte stuff nSkipData = Buf(m_nPos++); nSkipCount++; if (nSkipData == 0x00) { \/\/ Byte stuff nSkipData = 0xFF; } else if ((nSkipData >= JFIF_RST0) && (nSkipData <= JFIF_RST7)) { \/\/ Skip over } else { \/\/ Marker bSkipDone = true; m_nPos -= 2; } } if (m_pAppConfig->bOutputScanDump && (!bSkipDone) ) { \/\/ Only display 20 lines of scan data if (nSkipPos > 640) { if (!bScanDumpTrunc) { m_pLog->AddLineWarn(_T(\" WARNING: Dump truncated.\")); bScanDumpTrunc = TRUE; } } else { if ( ((nSkipPos-1) == 0) || (((nSkipPos-1) % 32) == 0) ) { strFull = _T(\" \"); } strTmp.Format(_T(\"%02x \"),nSkipData); strFull += strTmp; if (((nSkipPos-1) % 32) == 31) { m_pLog->AddLine(strFull); strFull = _T(\"\"); } } } \/\/ Did we run out of bytes? \/\/ FIXME: \/\/ NOTE: This line here doesn't allow us to attempt to \/\/ decode images that are missing EOI. Maybe this is \/\/ not the best solution here? Instead, we should be \/\/ checking m_nPos against file length? .. and not \/\/ return but \"break\". if (!m_pWBuf->GetBufOk()) { strTmp.Format(_T(\"ERROR: Ran out of buffer before EOI during phase 1 of Scan decode @ 0x%08X\"),m_nPos); m_pLog->AddLineErr(strTmp); break; } } m_pLog->AddLine(strFull); \/\/ } \/\/ --- PASS 2 --- \/\/ If the option is set, start parsing! if (m_pAppConfig->bDecodeScanImg && m_bImgSofUnsupported) { \/\/ SOF marker was of type we don't support, so skip decoding m_pLog->AddLineWarn(_T(\" NOTE: Scan parsing doesn't support this SOF mode.\")); #ifndef DEBUG_YCCK } else if (m_pAppConfig->bDecodeScanImg && (m_nSofNumComps_Nf == 4)) { m_pLog->AddLineWarn(_T(\" NOTE: Scan parsing doesn't support CMYK files yet.\")); #endif } else if (m_pAppConfig->bDecodeScanImg && !m_bImgSofUnsupported) { if (!m_bStateSofOk) { m_pLog->AddLineWarn(_T(\" NOTE: Scan decode disabled as SOF not decoded.\")); } else if (!m_bStateDqtOk) { m_pLog->AddLineWarn(_T(\" NOTE: Scan decode disabled as DQT not decoded.\")); } else if (!m_bStateDhtOk) { m_pLog->AddLineWarn(_T(\" NOTE: Scan decode disabled as DHT not decoded.\")); } else { m_pLog->AddLine(_T(\"\")); \/\/ Set the primary image details m_pImgDec->SetImageDetails(m_nSofSampsPerLine_X,m_nSofNumLines_Y, m_nSofNumComps_Nf,m_nSosNumCompScan_Ns,m_nImgRstEn,m_nImgRstInterval); \/\/ Only recalculate the scan decoding if we need to (i.e. file \/\/ changed, offset changed, scan option changed) \/\/ TODO: In order to decode multiple scans, we will need to alter the \/\/ way that m_pImgSrcDirty is set if (m_pImgSrcDirty) { m_pImgDec->DecodeScanImg(nPosScanStart,true,false); m_pImgSrcDirty = false; } } } m_bStateSosOk = true; break; case JFIF_DRI: unsigned nVal; nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" Length = %u\"),nLength); m_pLog->AddLine(strTmp); nVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3); \/\/ According to ITU-T spec B.2.4.4, we only expect \/\/ restart markers if DRI value is non-zero! m_nImgRstInterval = nVal; if (nVal != 0) { m_nImgRstEn = true; } else { m_nImgRstEn = false; } strTmp.Format(_T(\" interval = %u\"),m_nImgRstInterval); m_pLog->AddLine(strTmp); m_nPos += 4; if (!ExpectMarkerEnd(nPosMarkerStart,nLength)) return DECMARK_ERR; break; case JFIF_EOI: \/\/ EOI m_pLog->AddLine(_T(\"\")); \/\/ Save the EOI file position \/\/ NOTE: If the file is missing the EOI, then this variable will be \/\/ set to mark the end of file. m_nPosEmbedEnd = m_nPos; m_nPosEoi = m_nPos; m_bStateEoi = true; return DECMARK_EOI; break; \/\/ Markers that are not yet supported in JPEGsnoop case JFIF_DHP: \/\/ Markers defined for future use \/ extensions case JFIF_JPG: case JFIF_JPG0: case JFIF_JPG1: case JFIF_JPG2: case JFIF_JPG3: case JFIF_JPG4: case JFIF_JPG5: case JFIF_JPG6: case JFIF_JPG7: case JFIF_JPG8: case JFIF_JPG9: case JFIF_JPG10: case JFIF_JPG11: case JFIF_JPG12: case JFIF_JPG13: case JFIF_TEM: \/\/ Unsupported marker \/\/ - Provide generic decode based on length nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); \/\/ Length strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(\" Skipping unsupported marker\")); m_nPos += nLength; break; case JFIF_RST0: case JFIF_RST1: case JFIF_RST2: case JFIF_RST3: case JFIF_RST4: case JFIF_RST5: case JFIF_RST6: case JFIF_RST7: \/\/ We don't expect to see restart markers outside the entropy coded segment. \/\/ NOTE: RST# are standalone markers, so no length indicator exists \/\/ But for the sake of robustness, we can check here to see if treating \/\/ as a standalone marker will arrive at another marker (ie. OK). If not, \/\/ proceed to assume there is a length indicator. strTmp.Format(_T(\" WARNING: Restart marker [0xFF%02X] detected outside scan\"),nCode); m_pLog->AddLineWarn(strTmp); if (!m_pAppConfig->bRelaxedParsing) { \/\/ Abort m_pLog->AddLineErr(_T(\" Stopping decode\")); m_pLog->AddLine(_T(\" Use [Img Search Fwd\/Rev] to locate other valid embedded JPEGs\")); return DECMARK_ERR; } else { \/\/ Ignore \/\/ Check to see if standalone marker treatment looks OK if (Buf(m_nPos+2) == 0xFF) { \/\/ Looks like standalone m_pLog->AddLineWarn(_T(\" Ignoring standalone marker. Proceeding with decode.\")); m_nPos += 2; } else { \/\/ Looks like marker with length nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(\" Skipping marker\")); m_nPos += nLength; } } break; default: strTmp.Format(_T(\" WARNING: Unknown marker [0xFF%02X]\"),nCode); m_pLog->AddLineWarn(strTmp); if (!m_pAppConfig->bRelaxedParsing) { \/\/ Abort m_pLog->AddLineErr(_T(\" Stopping decode\")); m_pLog->AddLine(_T(\" Use [Img Search Fwd\/Rev] to locate other valid embedded JPEGs\")); return DECMARK_ERR; } else { \/\/ Skip nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); strTmp.Format(_T(\" Header length = %u\"),nLength); m_pLog->AddLine(strTmp); m_pLog->AddLineWarn(_T(\" Skipping marker\")); m_nPos += nLength; } } \/\/ Add white-space between each marker m_pLog->AddLine(_T(\" \")); \/\/ If we decided to abort for any reason, make sure we trap it now. \/\/ This will stop the ProcessFile() while loop. We can set m_bStateAbort \/\/ if user says that they want to stop. if (m_bStateAbort) { return DECMARK_ERR; } return DECMARK_OK; }","output":{"is_vulnerable":"True","vulnerability_types":["Divide By Zero"],"explanation":"ImpulseAdventure JPEGsnoop version 1.7.5 is vulnerable to a division by zero in the JFIF decode handling resulting denial of service.","severity_level":"Medium","cwe":"CWE-369","cve":"CVE-2017-1000414"}} -{"idx":341815,"input":"void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x0116; ushort table_buf_0x0116_len = 0; uchar *table_buf_0x2010; ushort table_buf_0x2010_len = 0; uchar *table_buf_0x9050; ushort table_buf_0x9050_len = 0; uchar *table_buf_0x9400; ushort table_buf_0x9400_len = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_len = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_len = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_len = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_len = 0; uchar *table_buf_0x940e; ushort table_buf_0x940e_len = 0; INT64 fsize = ifp->size(); #endif \/* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. *\/ if (!strncmp(make, \"Nokia\", 5)) return; fread(buf, 1, 10, ifp); \/* printf(\"===>>buf: 0x\"); for (int i = 0; i < sizeof buf; i ++) { printf(\"%02x\", buf[i]); } putchar('\\n'); *\/ if (!strncmp(buf, \"KDK\", 3) || \/* these aren't TIFF tables *\/ !strncmp(buf, \"VER\", 3) || !strncmp(buf, \"IIII\", 4) || !strncmp(buf, \"MMMM\", 4)) return; if (!strncmp(buf, \"KC\", 2) || \/* Konica KD-400Z, KD-510Z *\/ !strncmp(buf, \"MLY\", 3)) { \/* Minolta DiMAGE G series *\/ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, \"Nikon\")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, \"OLYMPUS\") || !strcmp(buf, \"PENTAX \")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, \"SONY\", 4) || !strcmp(buf, \"Panasonic\")) { goto nf; } else if (!strncmp(buf, \"FUJIFILM\", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, \"OLYMP\") || !strcmp(buf, \"LEICA\") || !strcmp(buf, \"Ricoh\") || !strcmp(buf, \"EPSON\")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, \"AOC\") || !strcmp(buf, \"QVC\")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, \"SAMSUNG\", 7)) base = ftell(ifp); } \/\/ adjust pos & base for Leica M8\/M9\/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, \"LEICA\", 5)) { if (!strncmp(model, \"M8\", 2) || !strncasecmp(model, \"Leica M8\", 8) || !strncasecmp(model, \"LEICA X\", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, \"LEICA M (Typ 240)\", 17)) { base = 0; } else if (!strncmp(model, \"M9\", 2) || !strncasecmp(model, \"Leica M9\", 8) || !strncasecmp(model, \"M Monochrom\", 11) || !strncasecmp(model, \"Leica M Monochrom\", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, \"LEICA T\", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, \"LEICA SL\", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); \/\/ Recover tiff-read position!! continue; } if (!strncasecmp(model, \"KODAK P880\", 10) || !strncasecmp(model, \"KODAK P850\", 10) || !strncasecmp(model, \"KODAK P712\", 10)) { if (tag == 0xf90b) { imgdata.makernotes.kodak.clipBlack = get2(); } else if (tag == 0xf90c) { imgdata.makernotes.kodak.clipWhite = get2(); } } if (!strncmp(make, \"Canon\", 5)) { if (tag == 0x000d && len < 256000) \/\/ camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16, len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) \/\/ Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, \"FUJI\", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), \"%s %s\", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = MIN((sizeof(ynum)-1), (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18); strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, \"%2x\", &c); j += 2) ystr[j \/ 2] = c; ystr[ynum_len \/ 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), \"%s %s %d:%s:%s\", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), \"%s %d:%s:%s %s\", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), \"%s %s %d:%s:%s %s\", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, \"Hasselblad X1D\", 14) || !strncasecmp(model, \"Hasselblad H6D\", 14) || !strncasecmp(model, \"Hasselblad A6D\", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, \"LEICA\", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, \"Leica Camera AG\", 15) && !strncmp(buf, \"LEICA\", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, \"LEICA M\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, \"LEICA S\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, \"NIKON\", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) \/ (float)c; } else if (tag == 0x003b) \/\/ all 1s for regular exposures { imgdata.makernotes.nikon.ME_WB[0] = getreal(type); imgdata.makernotes.nikon.ME_WB[2] = getreal(type); imgdata.makernotes.nikon.ME_WB[1] = getreal(type); imgdata.makernotes.nikon.ME_WB[3] = getreal(type); } else if (tag == 0x0045) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x0082) \/\/ lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) \/\/ lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) \/\/ lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) \/\/ lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 \/ c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops \/ 12.0f; } } else if (tag == 0x0093) \/\/ Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) \/\/ contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: \/\/ encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) \/\/ contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); \/\/ ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } else if (tag == 0x00b9) { uchar uc; int8_t sc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTune = uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneIndex = uc; fread(&sc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneAdj = sc; } } else if (!strncmp(make, \"OLYMPUS\", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) \/ 2); break; case 0x20400612: case 0x30000612: imgdata.sizes.raw_crop.cleft = get2(); break; case 0x20400613: case 0x30000613: imgdata.sizes.raw_crop.ctop = get2(); break; case 0x20400614: case 0x30000614: imgdata.sizes.raw_crop.cwidth = get2(); break; case 0x20400615: case 0x30000615: imgdata.sizes.raw_crop.cheight = get2(); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(sqrt(2.0f), get2() \/ 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float)temp; else imgdata.other.CameraTemperature = (float)(temp - 32) \/ 1.8f; if ((OlyID == 0x4434353933ULL) && \/\/ TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || \/\/ E-1 (OlyID == 0x5330303336ULL) || \/\/ E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(make, \"RICOH\", 5)) && !strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { \/\/ sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, \"%02x\", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, \"%8s\", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, \"%02x%02x%02x%02x\", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%02x%02x%02x%02x\", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, \"RICOH\", 5) && strncmp(model, \"PENTAX\", 6)) { if ((tag == 0x0005) && !strncmp(model, \"GXR\", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%8s\", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, \"Wide-Angle Adapter\"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, \"GXR\", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, \"PENTAX\", 6) || !strncmp(model, \"PENTAX\", 6) || (!strncmp(make, \"SAMSUNG\", 7) && dng_version)) && strncmp(model, \"GR\", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x000d) { imgdata.makernotes.pentax.FocusMode = get2(); } else if (tag == 0x000e) { imgdata.makernotes.pentax.AFPointSelected = get2(); } else if (tag == 0x000f) { imgdata.makernotes.pentax.AFPointsInFocus = getint(type); } else if (tag == 0x0010) { imgdata.makernotes.pentax.FocusPosition = get2(); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() \/ 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() \/ 100.0f; } else if (tag == 0x0034) { uchar uc; FORC4 { fread(&uc, 1, 1, ifp); imgdata.makernotes.pentax.DriveMode[c] = uc; } } else if (tag == 0x0038) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); } else if (tag == 0x0039) { imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) \/ 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) \/ 6.0f; } else if (tag == 0x0072) { imgdata.makernotes.pentax.AFAdjustment = get2(); } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) \/\/ Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) \/ sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, \"%d\", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) \/\/ Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, \" \"); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, \"SAMSUNG\", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, \"NX mini\", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float)temp; if (get4() == 10) imgdata.other.CameraTemperature \/= 10.0f; } } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() \/ 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, \"SONY\", 4) || !strncasecmp(make, \"Konica\", 6) || !strncasecmp(make, \"Minolta\", 7) || (!strncasecmp(make, \"Hasselblad\", 10) && (!strncasecmp(model, \"Stellar\", 7) || !strncasecmp(model, \"Lunar\", 5) || !strncasecmp(model, \"Lusso\", 5) || !strncasecmp(model, \"HV\", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010, table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400, table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403, table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c, table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, \"NIKON\") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, \"NIKON\") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * libraw_powf64l(2.0f, float(cc) \/ 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64l(2.0, i \/ 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = libraw_powf64l(2.0, i \/ 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = libraw_powf64l(2.0, (short)i \/ -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, \"KONICA\", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, \"Canon\", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 \/* Canon rotation data is handled by EXIF.Orientation *\/ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = \"065\"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, \"Olympus\", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, \"E-410\", 5) || !strncasecmp(model, \"E-510\", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, \"v757-71\")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, \"v757-71\")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200306) { uchar uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.olympus.AFFineTune = uc; } if (tag == 0x20200307) { FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2(); } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, \"NIKON\", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, \"NRW \", 4)) { fseek(ifp, strcmp(buf + 4, \"0100\") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, \"PENTAX\")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, \"D50\"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, \"%d\", serial); #endif } if (tag == 0x29 && type == 1) { \/\/ Canon PowerShot G9 c = wbi < 18 ? \"012347800000005896\"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, \"Samsung\", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { \/\/ shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = \"66666>666;6A;:;55\"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) \/\/ Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) \/\/ Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) \/\/ Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) \/\/ Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD \/\/ not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, \"NIKON\") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { \/* Nikon Capture Note *\/ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 \/ 0x10000; cam_mul[2] = get2() * 382 * 1.173 \/ 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, \"v757-71\")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) \/ 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) \/ 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) \/ 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() \/ 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() \/ 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() \/ 256.0; cam_mul[2] = get2() \/ 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD \/\/ IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) && ((type == 7) || (type == 13)) && !strncasecmp(make, \"Olympus\", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } \/\/ IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, \"OLYMP\", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, \"Samsung\", 7)) { if (tag == 0xa020) \/\/ get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) \/\/ get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } \/* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf (\"Samsung 0xa025 %d\\n\", i); } *\/ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) \/ 256.0; #endif if (tag == 0xa031 && len == 9) \/\/ get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) \/ 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { \/\/ Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":466096,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if ((length > PNG_UINT_31_MAX) || (length > GetBlobSize(image)) || (count < 4)) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 9) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id >= MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS-1; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { \/* Read global PLTE. *\/ if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (((p-chunk) < (long) length) && *p) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; if (SetImageBackgroundColor(image,exception) == MagickFalse) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || (length % 2) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { if ((MagickSizeType) loop_iters > GetMagickResourceLimit(ListLengthResource)) loop_iters=GetMagickResourceLimit(ListLengthResource); if (loop_iters >= 2147483647L) loop_iters=2147483647L; mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] > 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { if (prev != (Quantum *) NULL) prev=(Quantum *) RelinquishMagickMemory(prev); if (next != (Quantum *) NULL) next=(Quantum *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (Quantum *) NULL) break; q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":160431,"input":"yyparse (void *yyscanner, YR_COMPILER* compiler) { \/* The lookahead symbol. *\/ int yychar; \/* The semantic value of the lookahead symbol. *\/ \/* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. *\/ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); \/* Number of syntax errors so far. *\/ int yynerrs; int yystate; \/* Number of tokens to shift before error messages enabled. *\/ int yyerrstatus; \/* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. *\/ \/* The state stack. *\/ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; \/* The semantic value stack. *\/ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; \/* Lookahead token as an internal (translated) token number. *\/ int yytoken = 0; \/* The variables used to return semantic value and location from the action routines. *\/ YYSTYPE yyval; #if YYERROR_VERBOSE \/* Buffer for error messages, and its allocated size. *\/ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) \/* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. *\/ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, \"Starting parse\\n\")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; \/* Cause a token to be read. *\/ goto yysetstate; \/*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*\/ yynewstate: \/* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. *\/ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { \/* Get the current used size of the three stacks, in elements. *\/ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { \/* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. *\/ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; \/* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. *\/ yyoverflow (YY_(\"memory exhausted\"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else \/* no yyoverflow *\/ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else \/* Extend the stack our own way. *\/ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif \/* no yyoverflow *\/ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, \"Stack size increased to %lu\\n\", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, \"Entering state %d\\n\", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; \/*-----------. | yybackup. | `-----------*\/ yybackup: \/* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. *\/ \/* First try to decide what to do without reference to lookahead token. *\/ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; \/* Not known => get a lookahead token if don't already have one. *\/ \/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. *\/ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, \"Reading a token: \")); yychar = yylex (&yylval, yyscanner, compiler); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, \"Now at end of input.\\n\")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT (\"Next token is\", yytoken, &yylval, &yylloc); } \/* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. *\/ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } \/* Count tokens shifted since error; after three, turn off error status. *\/ if (yyerrstatus) yyerrstatus--; \/* Shift the lookahead token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yytoken, &yylval, &yylloc); \/* Discard the shifted token. *\/ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; \/*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*\/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; \/*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*\/ yyreduce: \/* yyn is the number of a rule to reduce with. *\/ yylen = yyr2[yyn]; \/* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. *\/ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 8: #line 230 \"grammar.y\" \/* yacc.c:1646 *\/ { int result = yr_parser_reduce_import(yyscanner, (yyvsp[0].sized_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF(result != ERROR_SUCCESS); } #line 1661 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 9: #line 242 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_RULE* rule = yr_parser_reduce_rule_declaration_phase_1( yyscanner, (int32_t) (yyvsp[-2].integer), (yyvsp[0].c_string)); ERROR_IF(rule == NULL); (yyval.rule) = rule; } #line 1674 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 10: #line 251 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_RULE* rule = (yyvsp[-4].rule); \/\/ rule created in phase 1 rule->tags = (yyvsp[-3].c_string); rule->metas = (yyvsp[-1].meta); rule->strings = (yyvsp[0].string); } #line 1686 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 11: #line 259 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_RULE* rule = (yyvsp[-7].rule); \/\/ rule created in phase 1 compiler->last_result = yr_parser_reduce_rule_declaration_phase_2( yyscanner, rule); yr_free((yyvsp[-8].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1701 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 12: #line 274 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = NULL; } #line 1709 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 13: #line 278 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_META null_meta; memset(&null_meta, 0xFF, sizeof(YR_META)); null_meta.type = META_TYPE_NULL; compiler->last_result = yr_arena_write_data( compiler->metas_arena, &null_meta, sizeof(YR_META), NULL); (yyval.meta) = (yyvsp[0].meta); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1736 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 14: #line 305 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = NULL; } #line 1744 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 15: #line 309 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_STRING null_string; memset(&null_string, 0xFF, sizeof(YR_STRING)); null_string.g_flags = STRING_GFLAGS_NULL; compiler->last_result = yr_arena_write_data( compiler->strings_arena, &null_string, sizeof(YR_STRING), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.string) = (yyvsp[0].string); } #line 1771 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 17: #line 340 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = 0; } #line 1777 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 18: #line 341 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 1783 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 19: #line 346 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = RULE_GFLAGS_PRIVATE; } #line 1789 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 20: #line 347 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = RULE_GFLAGS_GLOBAL; } #line 1795 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 21: #line 353 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = NULL; } #line 1803 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 22: #line 357 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, \"\", NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[0].c_string); } #line 1821 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 23: #line 375 \"grammar.y\" \/* yacc.c:1646 *\/ { char* identifier; compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), &identifier); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = identifier; } #line 1838 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 24: #line 388 \"grammar.y\" \/* yacc.c:1646 *\/ { char* tag_name = (yyvsp[-1].c_string); size_t tag_length = tag_name != NULL ? strlen(tag_name) : 0; while (tag_length > 0) { if (strcmp(tag_name, (yyvsp[0].c_string)) == 0) { yr_compiler_set_error_extra_info(compiler, tag_name); compiler->last_result = ERROR_DUPLICATED_TAG_IDENTIFIER; break; } tag_name = (char*) yr_arena_next_address( yyget_extra(yyscanner)->sz_arena, tag_name, tag_length + 1); tag_length = tag_name != NULL ? strlen(tag_name) : 0; } if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), NULL); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-1].c_string); } #line 1874 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 25: #line 424 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = (yyvsp[0].meta); } #line 1880 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 26: #line 425 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = (yyvsp[-1].meta); } #line 1886 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 27: #line 431 \"grammar.y\" \/* yacc.c:1646 *\/ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_STRING, (yyvsp[-2].c_string), sized_string->c_string, 0); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.meta) == NULL); } #line 1906 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 28: #line 447 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-2].c_string), NULL, (yyvsp[0].integer)); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1923 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 29: #line 460 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-3].c_string), NULL, -(yyvsp[0].integer)); yr_free((yyvsp[-3].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1940 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 30: #line 473 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, TRUE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1957 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 31: #line 486 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, FALSE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1974 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 32: #line 502 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = (yyvsp[0].string); } #line 1980 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 33: #line 503 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = (yyvsp[-1].string); } #line 1986 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 34: #line 509 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->error_line = yyget_lineno(yyscanner); } #line 1994 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 35: #line 513 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer), (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2009 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 36: #line 524 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->error_line = yyget_lineno(yyscanner); } #line 2017 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 37: #line 528 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer) | STRING_GFLAGS_REGEXP, (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2033 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 38: #line 540 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, STRING_GFLAGS_HEXADECIMAL, (yyvsp[-2].c_string), (yyvsp[0].sized_string)); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.string) == NULL); } #line 2047 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 39: #line 553 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = 0; } #line 2053 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 40: #line 554 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 2059 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 41: #line 559 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_WIDE; } #line 2065 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 42: #line 560 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_ASCII; } #line 2071 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 43: #line 561 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_NO_CASE; } #line 2077 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 44: #line 562 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = STRING_GFLAGS_FULL_WORD; } #line 2083 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 45: #line 568 \"grammar.y\" \/* yacc.c:1646 *\/ { int var_index = yr_parser_lookup_loop_variable(yyscanner, (yyvsp[0].c_string)); if (var_index >= 0) { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, LOOP_LOCAL_VARS * var_index, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = compiler->loop_identifier[var_index]; } else { YR_OBJECT* object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), NULL); if (object == NULL) { char* ns = compiler->current_namespace->name; object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), ns); } if (object != NULL) { char* id; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &id); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_LOAD, id, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = object; (yyval.expression).identifier = object->identifier; } else { YR_RULE* rule = (YR_RULE*) yr_hash_table_lookup( compiler->rules_table, (yyvsp[0].c_string), compiler->current_namespace->name); if (rule != NULL) { compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH_RULE, rule, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = rule->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_UNDEFINED_IDENTIFIER; } } } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2172 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 46: #line 653 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_OBJECT* field = NULL; if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-2].expression).value.object->type == OBJECT_TYPE_STRUCTURE) { field = yr_object_lookup_field((yyvsp[-2].expression).value.object, (yyvsp[0].c_string)); if (field != NULL) { char* ident; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &ident); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_FIELD, ident, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = field; (yyval.expression).identifier = field->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_INVALID_FIELD_NAME; } } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-2].expression).identifier); compiler->last_result = ERROR_NOT_A_STRUCTURE; } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2222 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 47: #line 699 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_OBJECT_ARRAY* array; YR_OBJECT_DICTIONARY* dict; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_ARRAY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"array indexes must be of integer type\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_INDEX_ARRAY, NULL); array = (YR_OBJECT_ARRAY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = array->prototype_item; (yyval.expression).identifier = array->identifier; } else if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_DICTIONARY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_STRING) { yr_compiler_set_error_extra_info( compiler, \"dictionary keys must be of string type\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_LOOKUP_DICT, NULL); dict = (YR_OBJECT_DICTIONARY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = dict->prototype_item; (yyval.expression).identifier = dict->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_INDEXABLE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2283 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 48: #line 757 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_OBJECT_FUNCTION* function; char* args_fmt; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_FUNCTION) { compiler->last_result = yr_parser_check_types( compiler, (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object, (yyvsp[-1].c_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[-1].c_string), &args_fmt); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_CALL, args_fmt, NULL, NULL); function = (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = function->return_obj; (yyval.expression).identifier = function->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_A_FUNCTION; } yr_free((yyvsp[-1].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2328 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 49: #line 801 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = yr_strdup(\"\"); } #line 2334 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 50: #line 802 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = (yyvsp[0].c_string); } #line 2340 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 51: #line 807 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.c_string) = (char*) yr_malloc(MAX_FUNCTION_ARGS + 1); switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcpy((yyval.c_string), \"i\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcpy((yyval.c_string), \"f\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcpy((yyval.c_string), \"b\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcpy((yyval.c_string), \"s\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcpy((yyval.c_string), \"r\", MAX_FUNCTION_ARGS); break; } ERROR_IF((yyval.c_string) == NULL); } #line 2369 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 52: #line 832 \"grammar.y\" \/* yacc.c:1646 *\/ { if (strlen((yyvsp[-2].c_string)) == MAX_FUNCTION_ARGS) { compiler->last_result = ERROR_TOO_MANY_ARGUMENTS; } else { switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcat((yyvsp[-2].c_string), \"i\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcat((yyvsp[-2].c_string), \"f\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcat((yyvsp[-2].c_string), \"b\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcat((yyvsp[-2].c_string), \"s\", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcat((yyvsp[-2].c_string), \"r\", MAX_FUNCTION_ARGS); break; } } ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-2].c_string); } #line 2405 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 53: #line 868 \"grammar.y\" \/* yacc.c:1646 *\/ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); RE* re; RE_ERROR error; int re_flags = 0; if (sized_string->flags & SIZED_STRING_FLAGS_NO_CASE) re_flags |= RE_FLAGS_NO_CASE; if (sized_string->flags & SIZED_STRING_FLAGS_DOT_ALL) re_flags |= RE_FLAGS_DOT_ALL; compiler->last_result = yr_re_compile( sized_string->c_string, re_flags, compiler->re_code_arena, &re, &error); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_INVALID_REGULAR_EXPRESSION) yr_compiler_set_error_extra_info(compiler, error.message); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, re->root_node->forward_code, NULL, NULL); yr_re_destroy(re); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_REGEXP; } #line 2451 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 54: #line 914 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_STRING) { if ((yyvsp[0].expression).value.sized_string != NULL) { yywarning(yyscanner, \"Using literal string \\\"%s\\\" in a boolean operation.\", (yyvsp[0].expression).value.sized_string->c_string); } compiler->last_result = yr_parser_emit( yyscanner, OP_STR_TO_BOOL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2474 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 55: #line 936 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2487 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 56: #line 945 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 0, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2500 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 57: #line 954 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, \"matches\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_REGEXP, \"matches\"); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit( yyscanner, OP_MATCHES, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2519 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 58: #line 969 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, \"contains\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_STRING, \"contains\"); compiler->last_result = yr_parser_emit( yyscanner, OP_CONTAINS, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2535 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 59: #line 981 \"grammar.y\" \/* yacc.c:1646 *\/ { int result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_FOUND, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2553 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 60: #line 995 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"at\"); compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_AT, (yyvsp[0].expression).value.integer); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2570 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 61: #line 1008 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_IN, UNDEFINED); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result!= ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2585 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 62: #line 1019 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->loop_depth--; compiler->loop_identifier[compiler->loop_depth] = NULL; } #line 2594 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 63: #line 1024 \"grammar.y\" \/* yacc.c:1646 *\/ { int var_index; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \\ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; ERROR_IF(compiler->last_result != ERROR_SUCCESS); var_index = yr_parser_lookup_loop_variable( yyscanner, (yyvsp[-1].c_string)); if (var_index >= 0) { yr_compiler_set_error_extra_info( compiler, (yyvsp[-1].c_string)); compiler->last_result = \\ ERROR_DUPLICATED_LOOP_IDENTIFIER; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2628 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 64: #line 1054 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-1].integer) == INTEGER_SET_ENUMERATION) { yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); } else \/\/ INTEGER_SET_RANGE { yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset + 3, &addr, NULL); yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, NULL, NULL); } compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = (yyvsp[-4].c_string); compiler->loop_depth++; } #line 2667 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 65: #line 1089 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset; compiler->loop_depth--; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-5].integer) == INTEGER_SET_ENUMERATION) { yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); } else \/\/ INTEGER_SET_RANGE { yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 3, NULL, NULL); yr_parser_emit_with_arg_reloc( yyscanner, OP_JLE, compiler->loop_address[compiler->loop_depth], NULL, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); } yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); compiler->loop_identifier[compiler->loop_depth] = NULL; yr_free((yyvsp[-8].c_string)); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2750 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 66: #line 1168 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \\ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; if (compiler->loop_for_of_mem_offset != -1) compiler->last_result = \\ ERROR_NESTED_FOR_OF_LOOP; ERROR_IF(compiler->last_result != ERROR_SUCCESS); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); compiler->loop_for_of_mem_offset = mem_offset; compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = NULL; compiler->loop_depth++; } #line 2784 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 67: #line 1198 \"grammar.y\" \/* yacc.c:1646 *\/ { int mem_offset; compiler->loop_depth--; compiler->loop_for_of_mem_offset = -1; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2837 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 68: #line 1247 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit(yyscanner, OP_OF, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2847 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 69: #line 1253 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit(yyscanner, OP_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2857 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 70: #line 1259 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JFALSE, 0, \/\/ still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2887 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 71: #line 1285 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; uint8_t* and_addr; compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_AND, &and_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = compiler->fixup_stack_head; *(void**)(fixup->address) = (void*)(and_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2927 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 72: #line 1321 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JTRUE, 0, \/\/ still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2956 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 73: #line 1346 \"grammar.y\" \/* yacc.c:1646 *\/ { YR_FIXUP* fixup; uint8_t* or_addr; compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_OR, &or_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = compiler->fixup_stack_head; *(void**)(fixup->address) = (void*)(or_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2996 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 74: #line 1382 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"<\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3009 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 75: #line 1391 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \">\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3022 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 76: #line 1400 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"<=\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3035 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 77: #line 1409 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \">=\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3048 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 78: #line 1418 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"==\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3061 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 79: #line 1427 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"!=\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3074 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 80: #line 1436 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[0].expression); } #line 3082 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 81: #line 1440 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[-1].expression); } #line 3090 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 82: #line 1447 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = INTEGER_SET_ENUMERATION; } #line 3096 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 83: #line 1448 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.integer) = INTEGER_SET_RANGE; } #line 3102 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 84: #line 1454 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[-3].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for range's lower bound\"); compiler->last_result = ERROR_WRONG_TYPE; } if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for range's upper bound\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3124 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 85: #line 1476 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for enumeration item\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3140 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 86: #line 1488 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, \"wrong type for enumeration item\"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3155 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 87: #line 1503 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3164 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 89: #line 1509 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); yr_parser_emit_pushes_for_strings(yyscanner, \"$*\"); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3175 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 92: #line 1526 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3186 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 93: #line 1533 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3197 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 95: #line 1545 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3205 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 96: #line 1549 \"grammar.y\" \/* yacc.c:1646 *\/ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL); } #line 3213 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 97: #line 1557 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[-1].expression); } #line 3221 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 98: #line 1561 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit( yyscanner, OP_FILESIZE, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3235 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 99: #line 1571 \"grammar.y\" \/* yacc.c:1646 *\/ { yywarning(yyscanner, \"Using deprecated \\\"entrypoint\\\" keyword. Use the \\\"entry_point\\\" \" \"function from PE module instead.\"); compiler->last_result = yr_parser_emit( yyscanner, OP_ENTRYPOINT, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3253 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 100: #line 1585 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-1].expression), EXPRESSION_TYPE_INTEGER, \"intXXXX or uintXXXX\"); compiler->last_result = yr_parser_emit( yyscanner, (uint8_t) (OP_READ_INT + (yyvsp[-3].integer)), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3273 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 101: #line 1601 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, (yyvsp[0].integer), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = (yyvsp[0].integer); } #line 3287 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 102: #line 1611 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg_double( yyscanner, OP_PUSH, (yyvsp[0].double_), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } #line 3300 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 103: #line 1620 \"grammar.y\" \/* yacc.c:1646 *\/ { SIZED_STRING* sized_string; compiler->last_result = yr_arena_write_data( compiler->sz_arena, (yyvsp[0].sized_string), (yyvsp[0].sized_string)->length + sizeof(SIZED_STRING), (void**) &sized_string); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, sized_string, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = sized_string; } #line 3329 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 104: #line 1645 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_COUNT, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3345 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 105: #line 1657 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3361 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 106: #line 1669 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3381 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 107: #line 1685 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3397 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 108: #line 1697 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3417 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 109: #line 1713 \"grammar.y\" \/* yacc.c:1646 *\/ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) \/\/ loop identifier { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_BOOLEAN) \/\/ rule identifier { (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_OBJECT) { compiler->last_result = yr_parser_emit( yyscanner, OP_OBJ_VALUE, NULL); switch((yyvsp[0].expression).value.object->type) { case OBJECT_TYPE_INTEGER: (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; break; case OBJECT_TYPE_FLOAT: (yyval.expression).type = EXPRESSION_TYPE_FLOAT; break; case OBJECT_TYPE_STRING: (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = NULL; break; default: yr_compiler_set_error_extra_info_fmt( compiler, \"wrong usage of identifier \\\"%s\\\"\", (yyvsp[0].expression).identifier); compiler->last_result = ERROR_WRONG_TYPE; } } else { assert(FALSE); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3466 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 110: #line 1758 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT, \"-\"); if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : -((yyvsp[0].expression).value.integer); compiler->last_result = yr_parser_emit(yyscanner, OP_INT_MINUS, NULL); } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_FLOAT) { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; compiler->last_result = yr_parser_emit(yyscanner, OP_DBL_MINUS, NULL); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3489 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 111: #line 1777 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"+\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(+, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3511 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 112: #line 1795 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"-\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(-, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3533 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 113: #line 1813 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"*\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(*, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3555 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 114: #line 1831 \"grammar.y\" \/* yacc.c:1646 *\/ { compiler->last_result = yr_parser_reduce_operation( yyscanner, \"\\\\\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(\/, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3585 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 115: #line 1857 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"%\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"%\"); yr_parser_emit(yyscanner, OP_MOD, NULL); if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(%, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } #line 3607 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 116: #line 1875 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"^\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"^\"); yr_parser_emit(yyscanner, OP_BITWISE_XOR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(^, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3621 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 117: #line 1885 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"^\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"^\"); yr_parser_emit(yyscanner, OP_BITWISE_AND, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(&, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3635 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 118: #line 1895 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"|\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"|\"); yr_parser_emit(yyscanner, OP_BITWISE_OR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(|, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3649 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 119: #line 1905 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"~\"); yr_parser_emit(yyscanner, OP_BITWISE_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : ~((yyvsp[0].expression).value.integer); } #line 3663 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 120: #line 1915 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \"<<\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \"<<\"); yr_parser_emit(yyscanner, OP_SHL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(<<, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3677 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 121: #line 1925 \"grammar.y\" \/* yacc.c:1646 *\/ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, \">>\"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, \">>\"); yr_parser_emit(yyscanner, OP_SHR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(>>, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3691 \"grammar.c\" \/* yacc.c:1646 *\/ break; case 122: #line 1935 \"grammar.y\" \/* yacc.c:1646 *\/ { (yyval.expression) = (yyvsp[0].expression); } #line 3699 \"grammar.c\" \/* yacc.c:1646 *\/ break; #line 3703 \"grammar.c\" \/* yacc.c:1646 *\/ default: break; } \/* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. *\/ YY_SYMBOL_PRINT (\"-> $$ =\", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; \/* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. *\/ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; \/*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*\/ yyerrlab: \/* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. *\/ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); \/* If not already recovering from an error, report this error. *\/ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (yyscanner, compiler, YY_(\"syntax error\")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \\ yyssp, yytoken) { char const *yymsgp = YY_(\"syntax error\"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yyscanner, compiler, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { \/* If just tried and failed to reuse lookahead token after an error, discard it. *\/ if (yychar <= YYEOF) { \/* Return failure if at end of input. *\/ if (yychar == YYEOF) YYABORT; } else { yydestruct (\"Error: discarding\", yytoken, &yylval, yyscanner, compiler); yychar = YYEMPTY; } } \/* Else will try to reuse lookahead token after shifting the error token. *\/ goto yyerrlab1; \/*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*\/ yyerrorlab: \/* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. *\/ if (\/*CONSTCOND*\/ 0) goto yyerrorlab; \/* Do not reclaim the symbols of the rule whose action triggered this YYERROR. *\/ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; \/*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*\/ yyerrlab1: yyerrstatus = 3; \/* Each real token shifted decrements this. *\/ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } \/* Pop the current state because it cannot handle the error token. *\/ if (yyssp == yyss) YYABORT; yydestruct (\"Error: popping\", yystos[yystate], yyvsp, yyscanner, compiler); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END \/* Shift the error token. *\/ YY_SYMBOL_PRINT (\"Shifting\", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; \/*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*\/ yyacceptlab: yyresult = 0; goto yyreturn; \/*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*\/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE \/*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*\/ yyexhaustedlab: yyerror (yyscanner, compiler, YY_(\"memory exhausted\")); yyresult = 2; \/* Fall through. *\/ #endif yyreturn: if (yychar != YYEMPTY) { \/* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. *\/ yytoken = YYTRANSLATE (yychar); yydestruct (\"Cleanup: discarding lookahead\", yytoken, &yylval, yyscanner, compiler); } \/* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. *\/ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct (\"Cleanup: popping\", yystos[*yyssp], yyvsp, yyscanner, compiler); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":324867,"input":"template CImg& _draw_object3d(void *const pboard, CImg& zbuffer, const float X, const float Y, const float Z, const CImg& vertices, const CImgList& primitives, const CImgList& colors, const to& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, const float sprite_scale) { typedef typename cimg::superset2::type tpfloat; typedef typename to::value_type _to; if (is_empty() || !vertices || !primitives) return *this; CImg error_message(1024); if (!vertices.is_object3d(primitives,colors,opacities,false,error_message)) throw CImgArgumentException(_cimg_instance \"draw_object3d(): Invalid specified 3D object (%u,%u) (%s).\", cimg_instance,vertices._width,primitives._width,error_message.data()); #ifndef cimg_use_board if (pboard) return *this; #endif if (render_type==5) cimg::mutex(10); \/\/ Static variable used in this case, breaks thread-safety const float nspec = 1 - (specular_lightness<0.f?0.f:(specular_lightness>1.f?1.f:specular_lightness)), nspec2 = 1 + (specular_shininess<0.f?0.f:specular_shininess), nsl1 = (nspec2 - 1)\/cimg::sqr(nspec - 1), nsl2 = 1 - 2*nsl1*nspec, nsl3 = nspec2 - nsl1 - nsl2; \/\/ Create light texture for phong-like rendering. CImg light_texture; if (render_type==5) { if (colors._width>primitives._width) { static CImg default_light_texture; static const tc *lptr = 0; static tc ref_values[64] = { 0 }; const CImg& img = colors.back(); bool is_same_texture = (lptr==img._data); if (is_same_texture) for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) if (ref_values[r++]!=img(i*img._width\/9,j*img._height\/9,0,(i + j)%img._spectrum)) { is_same_texture = false; break; } if (!is_same_texture || default_light_texture._spectrum<_spectrum) { (default_light_texture.assign(img,false)\/=255).resize(-100,-100,1,_spectrum); lptr = colors.back().data(); for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) ref_values[r++] = img(i*img._width\/9,j*img._height\/9,0,(i + j)%img._spectrum); } light_texture.assign(default_light_texture,true); } else { static CImg default_light_texture; static float olightx = 0, olighty = 0, olightz = 0, ospecular_shininess = 0; if (!default_light_texture || lightx!=olightx || lighty!=olighty || lightz!=olightz || specular_shininess!=ospecular_shininess || default_light_texture._spectrum<_spectrum) { default_light_texture.assign(512,512); const float dlx = lightx - X, dly = lighty - Y, dlz = lightz - Z, nl = cimg::hypot(dlx,dly,dlz), nlx = (default_light_texture._width - 1)\/2*(1 + dlx\/nl), nly = (default_light_texture._height - 1)\/2*(1 + dly\/nl), white[] = { 1 }; default_light_texture.draw_gaussian(nlx,nly,default_light_texture._width\/3.f,white); cimg_forXY(default_light_texture,x,y) { const float factor = default_light_texture(x,y); if (factor>nspec) default_light_texture(x,y) = std::min(2.f,nsl1*factor*factor + nsl2*factor + nsl3); } default_light_texture.resize(-100,-100,1,_spectrum); olightx = lightx; olighty = lighty; olightz = lightz; ospecular_shininess = specular_shininess; } light_texture.assign(default_light_texture,true); } } \/\/ Compute 3D to 2D projection. CImg projections(vertices._width,2); tpfloat parallzmin = cimg::type::max(); const float absfocale = focale?cimg::abs(focale):0; if (absfocale) { cimg_pragma_openmp(parallel for cimg_openmp_if_size(projections.size(),4096)) cimg_forX(projections,l) { \/\/ Perspective projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); const tpfloat projectedz = z + Z + absfocale; projections(l,1) = Y + absfocale*y\/projectedz; projections(l,0) = X + absfocale*x\/projectedz; } } else { cimg_pragma_openmp(parallel for cimg_openmp_if_size(projections.size(),4096)) cimg_forX(projections,l) { \/\/ Parallel projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); if (z visibles(primitives._width,1,1,1,~0U); CImg zrange(primitives._width); const tpfloat zmin = absfocale?(tpfloat)(1.5f - absfocale):cimg::type::min(); bool is_forward = zbuffer?true:false; cimg_pragma_openmp(parallel for cimg_openmp_if_size(primitives.size(),4096)) cimglist_for(primitives,l) { const CImg& primitive = primitives[l]; switch (primitive.size()) { case 1 : { \/\/ Point CImg<_to> _opacity; __draw_object3d(opacities,l,_opacity); if (l<=colors.width() && (colors[l].size()!=_spectrum || _opacity)) is_forward = false; const unsigned int i0 = (unsigned int)primitive(0); const tpfloat z0 = Z + vertices(i0,2); if (z0>zmin) { visibles(l) = (unsigned int)l; zrange(l) = z0; } } break; case 5 : { \/\/ Sphere const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat Xc = 0.5f*((float)vertices(i0,0) + (float)vertices(i1,0)), Yc = 0.5f*((float)vertices(i0,1) + (float)vertices(i1,1)), Zc = 0.5f*((float)vertices(i0,2) + (float)vertices(i1,2)), _zc = Z + Zc, zc = _zc + _focale, xc = X + Xc*(absfocale?absfocale\/zc:1), yc = Y + Yc*(absfocale?absfocale\/zc:1), radius = 0.5f*cimg::hypot(vertices(i1,0) - vertices(i0,0), vertices(i1,1) - vertices(i0,1), vertices(i1,2) - vertices(i0,2))*(absfocale?absfocale\/zc:1), xm = xc - radius, ym = yc - radius, xM = xc + radius, yM = yc + radius; if (xM>=0 && xm<_width && yM>=0 && ym<_height && _zc>zmin) { visibles(l) = (unsigned int)l; zrange(l) = _zc; } is_forward = false; } break; case 2 : case 6 : { \/\/ Segment const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2); tpfloat xm, xM, ym, yM; if (x0=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1)\/2; } } break; case 3 : case 9 : { \/\/ Triangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2); tpfloat xm, xM, ym, yM; if (x0xM) xM = x2; if (y0yM) yM = y2; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin) { const tpfloat d = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0); if (is_double_sided || d<0) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1 + z2)\/3; } } } break; case 4 : case 12 : { \/\/ Quadrangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = (unsigned int)primitive(3); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2), x3 = projections(i3,0), y3 = projections(i3,1), z3 = Z + vertices(i3,2); tpfloat xm, xM, ym, yM; if (x0xM) xM = x2; if (x3xM) xM = x3; if (y0yM) yM = y2; if (y3yM) yM = y3; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin && z3>zmin) { const float d = (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0); if (is_double_sided || d<0) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1 + z2 + z3)\/4; } } } break; default : if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance \"draw_object3d(): Invalid primitive[%u] with size %u \" \"(should have size 1,2,3,4,5,6,9 or 12).\", cimg_instance, l,primitive.size()); } } \/\/ Force transparent primitives to be drawn last when zbuffer is activated \/\/ (and if object contains no spheres or sprites). if (is_forward) cimglist_for(primitives,l) if (___draw_object3d(opacities,l)!=1) zrange(l) = 2*zmax - zrange(l); \/\/ Sort only visibles primitives. unsigned int *p_visibles = visibles._data; tpfloat *p_zrange = zrange._data; const tpfloat *ptrz = p_zrange; cimg_for(visibles,ptr,unsigned int) { if (*ptr!=~0U) { *(p_visibles++) = *ptr; *(p_zrange++) = *ptrz; } ++ptrz; } const unsigned int nb_visibles = (unsigned int)(p_zrange - zrange._data); if (!nb_visibles) { if (render_type==5) cimg::mutex(10,0); return *this; } CImg permutations; CImg(zrange._data,nb_visibles,1,1,1,true).sort(permutations,is_forward); \/\/ Compute light properties CImg lightprops; switch (render_type) { case 3 : { \/\/ Flat Shading lightprops.assign(nb_visibles); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) cimg_forX(lightprops,l) { const CImg& primitive = primitives(visibles(permutations(l))); const unsigned int psize = (unsigned int)primitive.size(); if (psize==3 || psize==4 || psize==9 || psize==12) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nx = dy1*dz2 - dz1*dy2, ny = dz1*dx2 - dx1*dz2, nz = dx1*dy2 - dy1*dx2, norm = 1e-5f + cimg::hypot(nx,ny,nz), lx = X + (x0 + x1 + x2)\/3 - lightx, ly = Y + (y0 + y1 + y2)\/3 - lighty, lz = Z + (z0 + z1 + z2)\/3 - lightz, nl = 1e-5f + cimg::hypot(lx,ly,lz), factor = std::max(cimg::abs(-lx*nx - ly*ny - lz*nz)\/(norm*nl),(tpfloat)0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } else lightprops[l] = 1; } } break; case 4 : \/\/ Gouraud Shading case 5 : { \/\/ Phong-Shading CImg vertices_normals(vertices._width,6,1,1,0); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) for (int l = 0; l<(int)nb_visibles; ++l) { const CImg& primitive = primitives[visibles(l)]; const unsigned int psize = (unsigned int)primitive.size(); const bool triangle_flag = (psize==3) || (psize==9), quadrangle_flag = (psize==4) || (psize==12); if (triangle_flag || quadrangle_flag) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = quadrangle_flag?(unsigned int)primitive(3):0; const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nnx = dy1*dz2 - dz1*dy2, nny = dz1*dx2 - dx1*dz2, nnz = dx1*dy2 - dy1*dx2, norm = 1e-5f + cimg::hypot(nnx,nny,nnz), nx = nnx\/norm, ny = nny\/norm, nz = nnz\/norm; unsigned int ix = 0, iy = 1, iz = 2; if (is_double_sided && nz>0) { ix = 3; iy = 4; iz = 5; } vertices_normals(i0,ix)+=nx; vertices_normals(i0,iy)+=ny; vertices_normals(i0,iz)+=nz; vertices_normals(i1,ix)+=nx; vertices_normals(i1,iy)+=ny; vertices_normals(i1,iz)+=nz; vertices_normals(i2,ix)+=nx; vertices_normals(i2,iy)+=ny; vertices_normals(i2,iz)+=nz; if (quadrangle_flag) { vertices_normals(i3,ix)+=nx; vertices_normals(i3,iy)+=ny; vertices_normals(i3,iz)+=nz; } } } if (is_double_sided) cimg_forX(vertices_normals,p) { const float nx0 = vertices_normals(p,0), ny0 = vertices_normals(p,1), nz0 = vertices_normals(p,2), nx1 = vertices_normals(p,3), ny1 = vertices_normals(p,4), nz1 = vertices_normals(p,5), n0 = nx0*nx0 + ny0*ny0 + nz0*nz0, n1 = nx1*nx1 + ny1*ny1 + nz1*nz1; if (n1>n0) { vertices_normals(p,0) = -nx1; vertices_normals(p,1) = -ny1; vertices_normals(p,2) = -nz1; } } if (render_type==4) { lightprops.assign(vertices._width); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = 1e-5f + cimg::hypot(nx,ny,nz), lx = X + vertices(l,0) - lightx, ly = Y + vertices(l,1) - lighty, lz = Z + vertices(l,2) - lightz, nl = 1e-5f + cimg::hypot(lx,ly,lz), factor = std::max((-lx*nx - ly*ny - lz*nz)\/(norm*nl),(tpfloat)0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } } else { const unsigned int lw2 = light_texture._width\/2 - 1, lh2 = light_texture._height\/2 - 1; lightprops.assign(vertices._width,2); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = 1e-5f + cimg::hypot(nx,ny,nz), nnx = nx\/norm, nny = ny\/norm; lightprops(l,0) = lw2*(1 + nnx); lightprops(l,1) = lh2*(1 + nny); } } } break; } \/\/ Draw visible primitives const CImg default_color(1,_spectrum,1,1,(tc)200); CImg<_to> _opacity; for (unsigned int l = 0; l& primitive = primitives[n_primitive]; const CImg &__color = n_primitive(), _color = (__color && __color.size()!=_spectrum && __color._spectrum<_spectrum)? __color.get_resize(-100,-100,-100,_spectrum,0):CImg(), &color = _color?_color:(__color?__color:default_color); const tc *const pcolor = color._data; float opacity = __draw_object3d(opacities,n_primitive,_opacity); if (_opacity.is_empty()) opacity*=g_opacity; #ifdef cimg_use_board LibBoard::Board &board = *(LibBoard::Board*)pboard; #endif switch (primitive.size()) { case 1 : { \/\/ Colored point or sprite const unsigned int n0 = (unsigned int)primitive[0]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)); if (_opacity.is_empty()) { \/\/ Scalar opacity if (color.size()==_spectrum) { \/\/ Colored point draw_point(x0,y0,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height()-(float)y0); } #endif } else { \/\/ Sprite const tpfloat z = Z + vertices(n0,2); const float factor = focale<0?1:sprite_scale*(absfocale?absfocale\/(z + absfocale):1); const unsigned int _sw = (unsigned int)(color._width*factor), _sh = (unsigned int)(color._height*factor), sw = _sw?_sw:1, sh = _sh?_sh:1; const int nx0 = x0 - (int)sw\/2, ny0 = y0 - (int)sh\/2; if (sw<=3*_width\/2 && sh<=3*_height\/2 && (nx0 + (int)sw\/2>=0 || nx0 - (int)sw\/2=0 || ny0 - (int)sh\/2 _sprite = (sw!=color._width || sh!=color._height)? color.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg(), &sprite = _sprite?_sprite:color; draw_image(nx0,ny0,sprite,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128); board.setFillColor(LibBoard::Color::Null); board.drawRectangle((float)nx0,height() - (float)ny0,sw,sh); } #endif } } } else { \/\/ Opacity mask const tpfloat z = Z + vertices(n0,2); const float factor = focale<0?1:sprite_scale*(absfocale?absfocale\/(z + absfocale):1); const unsigned int _sw = (unsigned int)(std::max(color._width,_opacity._width)*factor), _sh = (unsigned int)(std::max(color._height,_opacity._height)*factor), sw = _sw?_sw:1, sh = _sh?_sh:1; const int nx0 = x0 - (int)sw\/2, ny0 = y0 - (int)sh\/2; if (sw<=3*_width\/2 && sh<=3*_height\/2 && (nx0 + (int)sw\/2>=0 || nx0 - (int)sw\/2=0 || ny0 - (int)sh\/2 _sprite = (sw!=color._width || sh!=color._height)? color.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg(), &sprite = _sprite?_sprite:color; const CImg<_to> _nopacity = (sw!=_opacity._width || sh!=_opacity._height)? _opacity.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg<_to>(), &nopacity = _nopacity?_nopacity:_opacity; draw_image(nx0,ny0,sprite,nopacity,g_opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128); board.setFillColor(LibBoard::Color::Null); board.drawRectangle((float)nx0,height() - (float)ny0,sw,sh); } #endif } } } break; case 2 : { \/\/ Colored line const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,x1,height() - (float)y1); } #endif } else { draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); } #endif } } break; case 5 : { \/\/ Colored sphere const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], is_wireframe = (unsigned int)primitive[2]; const float Xc = 0.5f*((float)vertices(n0,0) + (float)vertices(n1,0)), Yc = 0.5f*((float)vertices(n0,1) + (float)vertices(n1,1)), Zc = 0.5f*((float)vertices(n0,2) + (float)vertices(n1,2)), zc = Z + Zc + _focale, xc = X + Xc*(absfocale?absfocale\/zc:1), yc = Y + Yc*(absfocale?absfocale\/zc:1), radius = 0.5f*cimg::hypot(vertices(n1,0) - vertices(n0,0), vertices(n1,1) - vertices(n0,1), vertices(n1,2) - vertices(n0,2))*(absfocale?absfocale\/zc:1); switch (render_type) { case 0 : draw_point((int)xc,(int)yc,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot(xc,height() - yc); } #endif break; case 1 : draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity,~0U); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.setFillColor(LibBoard::Color::Null); board.drawCircle(xc,height() - yc,radius); } #endif break; default : if (is_wireframe) draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity,~0U); else draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); if (!is_wireframe) board.fillCircle(xc,height() - yc,radius); else { board.setFillColor(LibBoard::Color::Null); board.drawCircle(xc,height() - yc,radius); } } #endif break; } } break; case 6 : { \/\/ Textured line if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance \"draw_object3d(): Undefined texture for line primitive [%u].\", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const int tx0 = (int)primitive[2], ty0 = (int)primitive[3], tx1 = (int)primitive[4], ty1 = (int)primitive[5], x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); } #endif } else { draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); } #endif } } break; case 3 : { \/\/ Colored triangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity).draw_point(x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity).draw_line(zbuffer,x0,y0,z0,x2,y2,z2,pcolor,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity).draw_line(x0,y0,x2,y2,pcolor,opacity). draw_line(x1,y1,x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x0,height() - (float)y0,(float)x2,height() - (float)y2); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor, lightprops(n0),lightprops(n1),lightprops(n2),opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,lightprops(n0),lightprops(n1),lightprops(n2),opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprops(n0), (float)x1,height() - (float)y1,lightprops(n1), (float)x2,height() - (float)y2,lightprops(n2)); } #endif break; case 5 : { const unsigned int lx0 = (unsigned int)cimg::uiround(lightprops(n0,0)), ly0 = (unsigned int)cimg::uiround(lightprops(n0,1)), lx1 = (unsigned int)cimg::uiround(lightprops(n1,0)), ly1 = (unsigned int)cimg::uiround(lightprops(n1,1)), lx2 = (unsigned int)cimg::uiround(lightprops(n2,0)), ly2 = (unsigned int)cimg::uiround(lightprops(n2,1)); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n0,0))), (int)(light_texture.height()\/2*(1 + lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n1,0))), (int)(light_texture.height()\/2*(1 + lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n2,0))), (int)(light_texture.height()\/2*(1 + lightprops(n2,1)))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); } #endif } break; } } break; case 4 : { \/\/ Colored quadrangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)), x3 = cimg::uiround(projections(n3,0)), y3 = cimg::uiround(projections(n3,1)), xc = (x0 + x1 + x2 + x3)\/4, yc = (y0 + y1 + y2 + y3)\/4; const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale, zc = (z0 + z1 + z2 + z3)\/4; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity). draw_point(x2,y2,pcolor,opacity).draw_point(x3,y3,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); board.drawDot((float)x3,height() - (float)y3); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity).draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opacity). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,pcolor,opacity).draw_line(zbuffer,x3,y3,z3,x0,y0,z0,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity).draw_line(x1,y1,x2,y2,pcolor,opacity). draw_line(x2,y2,x3,y3,pcolor,opacity).draw_line(x3,y3,x0,y0,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); board.drawLine((float)x2,height() - (float)y2,(float)x3,height() - (float)y3); board.drawLine((float)x3,height() - (float)y3,(float)x0,height() - (float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity).draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opacity,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity,lightprops(l)). _draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp),(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3), lightpropc = (lightprop0 + lightprop1 + lightprop2 + lightprop2)\/4; if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,xc,yc,zc,pcolor,lightprop0,lightprop1,lightpropc,opacity). draw_triangle(zbuffer,x1,y1,z1,x2,y2,z2,xc,yc,zc,pcolor,lightprop1,lightprop2,lightpropc,opacity). draw_triangle(zbuffer,x2,y2,z2,x3,y3,z3,xc,yc,zc,pcolor,lightprop2,lightprop3,lightpropc,opacity). draw_triangle(zbuffer,x3,y3,z3,x0,y0,z0,xc,yc,zc,pcolor,lightprop3,lightprop0,lightpropc,opacity); else draw_triangle(x0,y0,x1,y1,xc,yc,pcolor,lightprop0,lightprop1,lightpropc,opacity). draw_triangle(x1,y1,x2,y2,xc,yc,pcolor,lightprop1,lightprop2,lightpropc,opacity). draw_triangle(x2,y2,x3,y3,xc,yc,pcolor,lightprop2,lightprop3,lightpropc,opacity). draw_triangle(x3,y3,x0,y0,xc,yc,pcolor,lightprop3,lightprop0,lightpropc,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x1,height() - (float)y1,lightprop1, (float)x2,height() - (float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x2,height() - (float)y2,lightprop2, (float)x3,height() - (float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)cimg::uiround(lightprops(n0,0)), ly0 = (unsigned int)cimg::uiround(lightprops(n0,1)), lx1 = (unsigned int)cimg::uiround(lightprops(n1,0)), ly1 = (unsigned int)cimg::uiround(lightprops(n1,1)), lx2 = (unsigned int)cimg::uiround(lightprops(n2,0)), ly2 = (unsigned int)cimg::uiround(lightprops(n2,1)), lx3 = (unsigned int)cimg::uiround(lightprops(n3,0)), ly3 = (unsigned int)cimg::uiround(lightprops(n3,1)), lxc = (lx0 + lx1 + lx2 + lx3)\/4, lyc = (ly0 + ly1 + ly2 + ly3)\/4; if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,xc,yc,zc,pcolor,light_texture,lx0,ly0,lx1,ly1,lxc,lyc,opacity). draw_triangle(zbuffer,x1,y1,z1,x2,y2,z2,xc,yc,zc,pcolor,light_texture,lx1,ly1,lx2,ly2,lxc,lyc,opacity). draw_triangle(zbuffer,x2,y2,z2,x3,y3,z3,xc,yc,zc,pcolor,light_texture,lx2,ly2,lx3,ly3,lxc,lyc,opacity). draw_triangle(zbuffer,x3,y3,z3,x0,y0,z0,xc,yc,zc,pcolor,light_texture,lx3,ly3,lx0,ly0,lxc,lyc,opacity); else draw_triangle(x0,y0,x1,y1,xc,yc,pcolor,light_texture,lx0,ly0,lx1,ly1,lxc,lyc,opacity). draw_triangle(x1,y1,x2,y2,xc,yc,pcolor,light_texture,lx1,ly1,lx2,ly2,lxc,lyc,opacity). draw_triangle(x2,y2,x3,y3,xc,yc,pcolor,light_texture,lx2,ly2,lx3,ly3,lxc,lyc,opacity). draw_triangle(x3,y3,x0,y0,xc,yc,pcolor,light_texture,lx3,ly3,lx0,ly0,lxc,lyc,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()\/2*(1 + lx0)), (int)(light_texture.height()\/2*(1 + ly0))), l1 = light_texture((int)(light_texture.width()\/2*(1 + lx1)), (int)(light_texture.height()\/2*(1 + ly1))), l2 = light_texture((int)(light_texture.width()\/2*(1 + lx2)), (int)(light_texture.height()\/2*(1 + ly2))), l3 = light_texture((int)(light_texture.width()\/2*(1 + lx3)), (int)(light_texture.height()\/2*(1 + ly3))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x2,height() - (float)y2,l2, (float)x3,height() - (float)y3,l3); } #endif } break; } } break; case 9 : { \/\/ Textured triangle if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance \"draw_object3d(): Undefined texture for triangle primitive [%u].\", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2]; const int tx0 = (int)primitive[3], ty0 = (int)primitive[4], tx1 = (int)primitive[5], ty1 = (int)primitive[6], tx2 = (int)primitive[7], ty2 = (int)primitive[8], x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity). draw_point(x2,y2,color.get_vector_at(tx2<=0?0:tx2>=color.width()?color.width() - 1:tx2, ty2<=0?0:ty2>=color.height()?color.height() - 1:ty2)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(zbuffer,x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opacity). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x0,height() - (float)y0,(float)x2,height() - (float)y2); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprops(n0),lightprops(n1),lightprops(n2),opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprops(n0),lightprops(n1),lightprops(n2),opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprops(n0), (float)x1,height() - (float)y1,lightprops(n1), (float)x2,height() - (float)y2,lightprops(n2)); } #endif break; case 5 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n0,0))), (int)(light_texture.height()\/2*(1 + lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n1,0))), (int)(light_texture.height()\/2*(1 + lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n2,0))), (int)(light_texture.height()\/2*(1 + lightprops(n2,1)))); board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); } #endif break; } } break; case 12 : { \/\/ Textured quadrangle if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance \"draw_object3d(): Undefined texture for quadrangle primitive [%u].\", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3]; const int tx0 = (int)primitive[4], ty0 = (int)primitive[5], tx1 = (int)primitive[6], ty1 = (int)primitive[7], tx2 = (int)primitive[8], ty2 = (int)primitive[9], tx3 = (int)primitive[10], ty3 = (int)primitive[11], x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)), x3 = cimg::uiround(projections(n3,0)), y3 = cimg::uiround(projections(n3,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity). draw_point(x2,y2,color.get_vector_at(tx2<=0?0:tx2>=color.width()?color.width() - 1:tx2, ty2<=0?0:ty2>=color.height()?color.height() - 1:ty2)._data,opacity). draw_point(x3,y3,color.get_vector_at(tx3<=0?0:tx3>=color.width()?color.width() - 1:tx3, ty3<=0?0:ty3>=color.height()?color.height() - 1:ty3)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); board.drawDot((float)x3,height() - (float)y3); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opacity). draw_line(zbuffer,x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity). draw_line(x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opacity). draw_line(x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); board.drawLine((float)x2,height() - (float)y2,(float)x3,height() - (float)y3); board.drawLine((float)x3,height() - (float)y3,(float)x0,height() - (float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprop0,lightprop1,lightprop2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, lightprop0,lightprop2,lightprop3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprop0,lightprop1,lightprop2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, lightprop0,lightprop2,lightprop3,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x1,height() - (float)y1,lightprop1, (float)x2,height() - (float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height() -(float)y0,lightprop0, (float)x2,height() - (float)y2,lightprop2, (float)x3,height() - (float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)cimg::uiround(lightprops(n0,0)), ly0 = (unsigned int)cimg::uiround(lightprops(n0,1)), lx1 = (unsigned int)cimg::uiround(lightprops(n1,0)), ly1 = (unsigned int)cimg::uiround(lightprops(n1,1)), lx2 = (unsigned int)cimg::uiround(lightprops(n2,0)), ly2 = (unsigned int)cimg::uiround(lightprops(n2,1)), lx3 = (unsigned int)cimg::uiround(lightprops(n3,0)), ly3 = (unsigned int)cimg::uiround(lightprops(n3,1)); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()\/2*(1 + lx0)), (int)(light_texture.height()\/2*(1 + ly0))), l1 = light_texture((int)(light_texture.width()\/2*(1 + lx1)), (int)(light_texture.height()\/2*(1 + ly1))), l2 = light_texture((int)(light_texture.width()\/2*(1 + lx2)), (int)(light_texture.height()\/2*(1 + ly2))), l3 = light_texture((int)(light_texture.width()\/2*(1 + lx3)), (int)(light_texture.height()\/2*(1 + ly3))); board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); board.fillGouraudTriangle((float)x0,height() -(float)y0,l0, (float)x2,height() - (float)y2,l2, (float)x3,height() - (float)y3,l3); } #endif } break; } } break; } } if (render_type==5) cimg::mutex(10,0); return *this;","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":207767,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if ((length > PNG_UINT_31_MAX) || (length > GetBlobSize(image)) || (count < 4)) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 9) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id >= MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS-1; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { \/* Read global PLTE. *\/ if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (((p-chunk) < (long) length) && *p) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; if (SetImageBackgroundColor(image,exception) == MagickFalse) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || (length % 2) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { if ((MagickSizeType) loop_iters > GetMagickResourceLimit(ListLengthResource)) loop_iters=GetMagickResourceLimit(ListLengthResource); if (loop_iters >= 2147483647L) loop_iters=2147483647L; mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] > 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (((mng_info->magn_methx > 0) && (mng_info->magn_methx <= 5)) && ((mng_info->magn_methy > 0) && (mng_info->magn_methy <= 5))) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { if (prev != (Quantum *) NULL) prev=(Quantum *) RelinquishMagickMemory(prev); if (next != (Quantum *) NULL) next=(Quantum *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (Quantum *) NULL) break; q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers && image->next) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); image=DestroyImageList(image); if (next_image == (Image *) NULL) { mng_info=MngInfoFreeStruct(mng_info); return((Image *) NULL); } image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"True","vulnerability_types":["Use After Free"],"explanation":"In ImageMagick 7.0.9-7 Q16, there is a use-after-free in the function MngInfoDiscardObject of coders\/png.c, related to ReadOneMNGImage.","severity_level":"NoInfo","cwe":"CWE-416","cve":"CVE-2019-19952"}} -{"idx":209923,"input":"exec_instructions(ectx_T *ectx) { int ret = FAIL; int save_trylevel_at_start = ectx->ec_trylevel_at_start; int dict_stack_len_at_start = dict_stack.ga_len; \/\/ Start execution at the first instruction. ectx->ec_iidx = 0; \/\/ Only catch exceptions in this instruction list. ectx->ec_trylevel_at_start = trylevel; for (;;) { static int breakcheck_count = 0; \/\/ using \"static\" makes it faster isn_T *iptr; typval_T *tv; if (unlikely(++breakcheck_count >= 100)) { line_breakcheck(); breakcheck_count = 0; } if (unlikely(got_int)) { \/\/ Turn CTRL-C into an exception. got_int = FALSE; if (throw_exception(\"Vim:Interrupt\", ET_INTERRUPT, NULL) == FAIL) goto theend; did_throw = TRUE; } if (unlikely(did_emsg && msg_list != NULL && *msg_list != NULL)) { \/\/ Turn an error message into an exception. did_emsg = FALSE; if (throw_exception(*msg_list, ET_ERROR, NULL) == FAIL) goto theend; did_throw = TRUE; *msg_list = NULL; } if (unlikely(did_throw)) { garray_T *trystack = &ectx->ec_trystack; trycmd_T *trycmd = NULL; int index = trystack->ga_len; \/\/ An exception jumps to the first catch, finally, or returns from \/\/ the current function. while (index > 0) { trycmd = ((trycmd_T *)trystack->ga_data) + index - 1; if (!trycmd->tcd_in_catch || trycmd->tcd_finally_idx != 0) break; \/\/ In the catch and finally block of this try we have to go up \/\/ one level. --index; trycmd = NULL; } if (trycmd != NULL && trycmd->tcd_frame_idx == ectx->ec_frame_idx) { if (trycmd->tcd_in_catch) { \/\/ exception inside \":catch\", jump to \":finally\" once ectx->ec_iidx = trycmd->tcd_finally_idx; trycmd->tcd_finally_idx = 0; } else \/\/ jump to first \":catch\" ectx->ec_iidx = trycmd->tcd_catch_idx; trycmd->tcd_in_catch = TRUE; did_throw = FALSE; \/\/ don't come back here until :endtry trycmd->tcd_did_throw = TRUE; } else { \/\/ Not inside try or need to return from current functions. \/\/ Push a dummy return value. if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->v_type = VAR_NUMBER; tv->vval.v_number = 0; ++ectx->ec_stack.ga_len; if (ectx->ec_frame_idx == ectx->ec_initial_frame_idx) { \/\/ At the toplevel we are done. need_rethrow = TRUE; if (handle_closure_in_use(ectx, FALSE) == FAIL) goto theend; goto done; } if (func_return(ectx) == FAIL) goto theend; } continue; } iptr = &ectx->ec_instr[ectx->ec_iidx++]; switch (iptr->isn_type) { \/\/ execute Ex command line case ISN_EXEC: if (exec_command(iptr) == FAIL) goto on_error; break; \/\/ execute Ex command line split at NL characters. case ISN_EXEC_SPLIT: { source_cookie_T cookie; char_u *line; SOURCING_LNUM = iptr->isn_lnum; CLEAR_FIELD(cookie); cookie.sourcing_lnum = iptr->isn_lnum - 1; cookie.nextline = iptr->isn_arg.string; line = get_split_sourceline(0, &cookie, 0, 0); if (do_cmdline(line, get_split_sourceline, &cookie, DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED) == FAIL || did_emsg) { vim_free(line); goto on_error; } vim_free(line); } break; \/\/ execute Ex command line that is only a range case ISN_EXECRANGE: { exarg_T ea; char *error = NULL; CLEAR_FIELD(ea); ea.cmdidx = CMD_SIZE; ea.addr_type = ADDR_LINES; ea.cmd = iptr->isn_arg.string; parse_cmd_address(&ea, &error, FALSE); if (ea.cmd == NULL) goto on_error; if (error == NULL) error = ex_range_without_command(&ea); if (error != NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(error); goto on_error; } } break; \/\/ Evaluate an expression with legacy syntax, push it onto the \/\/ stack. case ISN_LEGACY_EVAL: { char_u *arg = iptr->isn_arg.string; int res; int save_flags = cmdmod.cmod_flags; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); init_tv(tv); cmdmod.cmod_flags |= CMOD_LEGACY; res = eval0(arg, tv, NULL, &EVALARG_EVALUATE); cmdmod.cmod_flags = save_flags; if (res == FAIL) goto on_error; ++ectx->ec_stack.ga_len; } break; \/\/ push typeval VAR_INSTR with instructions to be executed case ISN_INSTR: { if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->vval.v_instr = ALLOC_ONE(instr_T); if (tv->vval.v_instr == NULL) goto on_error; ++ectx->ec_stack.ga_len; tv->v_type = VAR_INSTR; tv->vval.v_instr->instr_ectx = ectx; tv->vval.v_instr->instr_instr = iptr->isn_arg.instr; } break; \/\/ execute :substitute with an expression case ISN_SUBSTITUTE: { subs_T *subs = &iptr->isn_arg.subs; source_cookie_T cookie; struct subs_expr_S *save_instr = substitute_instr; struct subs_expr_S subs_instr; int res; subs_instr.subs_ectx = ectx; subs_instr.subs_instr = subs->subs_instr; subs_instr.subs_status = OK; substitute_instr = &subs_instr; SOURCING_LNUM = iptr->isn_lnum; \/\/ This is very much like ISN_EXEC CLEAR_FIELD(cookie); cookie.sourcing_lnum = iptr->isn_lnum - 1; res = do_cmdline(subs->subs_cmd, getsourceline, &cookie, DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED); substitute_instr = save_instr; if (res == FAIL || did_emsg || subs_instr.subs_status == FAIL) goto on_error; } break; case ISN_FINISH: goto done; case ISN_REDIRSTART: \/\/ create a dummy entry for var_redir_str() if (alloc_redir_lval() == FAIL) goto on_error; \/\/ The output is stored in growarray \"redir_ga\" until \/\/ redirection ends. init_redir_ga(); redir_vname = 1; break; case ISN_REDIREND: { char_u *res = get_clear_redir_ga(); \/\/ End redirection, put redirected text on the stack. clear_redir_lval(); redir_vname = 0; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) { vim_free(res); goto theend; } tv = STACK_TV_BOT(0); tv->v_type = VAR_STRING; tv->vval.v_string = res; ++ectx->ec_stack.ga_len; } break; case ISN_CEXPR_AUCMD: #ifdef FEAT_QUICKFIX if (trigger_cexpr_autocmd(iptr->isn_arg.number) == FAIL) goto on_error; #endif break; case ISN_CEXPR_CORE: #ifdef FEAT_QUICKFIX { exarg_T ea; int res; CLEAR_FIELD(ea); ea.cmdidx = iptr->isn_arg.cexpr.cexpr_ref->cer_cmdidx; ea.forceit = iptr->isn_arg.cexpr.cexpr_ref->cer_forceit; ea.cmdlinep = &iptr->isn_arg.cexpr.cexpr_ref->cer_cmdline; --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); res = cexpr_core(&ea, tv); clear_tv(tv); if (res == FAIL) goto on_error; } #endif break; \/\/ execute Ex command from pieces on the stack case ISN_EXECCONCAT: { int count = iptr->isn_arg.number; size_t len = 0; int pass; int i; char_u *cmd = NULL; char_u *str; for (pass = 1; pass <= 2; ++pass) { for (i = 0; i < count; ++i) { tv = STACK_TV_BOT(i - count); str = tv->vval.v_string; if (str != NULL && *str != NUL) { if (pass == 2) STRCPY(cmd + len, str); len += STRLEN(str); } if (pass == 2) clear_tv(tv); } if (pass == 1) { cmd = alloc(len + 1); if (unlikely(cmd == NULL)) goto theend; len = 0; } } SOURCING_LNUM = iptr->isn_lnum; do_cmdline_cmd(cmd); vim_free(cmd); } break; \/\/ execute :echo {string} ... case ISN_ECHO: { int count = iptr->isn_arg.echo.echo_count; int atstart = TRUE; int needclr = TRUE; int idx; for (idx = 0; idx < count; ++idx) { tv = STACK_TV_BOT(idx - count); echo_one(tv, iptr->isn_arg.echo.echo_with_white, &atstart, &needclr); clear_tv(tv); } if (needclr) msg_clr_eos(); ectx->ec_stack.ga_len -= count; } break; \/\/ :execute {string} ... \/\/ :echomsg {string} ... \/\/ :echoconsole {string} ... \/\/ :echoerr {string} ... case ISN_EXECUTE: case ISN_ECHOMSG: case ISN_ECHOCONSOLE: case ISN_ECHOERR: { int count = iptr->isn_arg.number; garray_T ga; char_u buf[NUMBUFLEN]; char_u *p; int len; int failed = FALSE; int idx; ga_init2(&ga, 1, 80); for (idx = 0; idx < count; ++idx) { tv = STACK_TV_BOT(idx - count); if (iptr->isn_type == ISN_EXECUTE) { if (tv->v_type == VAR_CHANNEL || tv->v_type == VAR_JOB) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_using_invalid_value_as_string_str), vartype_name(tv->v_type)); break; } else p = tv_get_string_buf(tv, buf); } else p = tv_stringify(tv, buf); len = (int)STRLEN(p); if (GA_GROW_FAILS(&ga, len + 2)) failed = TRUE; else { if (ga.ga_len > 0) ((char_u *)(ga.ga_data))[ga.ga_len++] = ' '; STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p); ga.ga_len += len; } clear_tv(tv); } ectx->ec_stack.ga_len -= count; if (failed) { ga_clear(&ga); goto on_error; } if (ga.ga_data != NULL) { if (iptr->isn_type == ISN_EXECUTE) { SOURCING_LNUM = iptr->isn_lnum; do_cmdline_cmd((char_u *)ga.ga_data); if (did_emsg) { ga_clear(&ga); goto on_error; } } else { msg_sb_eol(); if (iptr->isn_type == ISN_ECHOMSG) { msg_attr(ga.ga_data, echo_attr); out_flush(); } else if (iptr->isn_type == ISN_ECHOCONSOLE) { ui_write(ga.ga_data, (int)STRLEN(ga.ga_data), TRUE); ui_write((char_u *)\"\\r\\n\", 2, TRUE); } else { SOURCING_LNUM = iptr->isn_lnum; emsg(ga.ga_data); } } } ga_clear(&ga); } break; \/\/ load local variable or argument case ISN_LOAD: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(STACK_TV_VAR(iptr->isn_arg.number), STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; break; \/\/ load v: variable case ISN_LOADV: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(get_vim_var_tv(iptr->isn_arg.number), STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; break; \/\/ load s: variable in Vim9 script case ISN_LOADSCRIPT: { scriptref_T *sref = iptr->isn_arg.script.scriptref; svar_T *sv; sv = get_script_svar(sref, ectx->ec_dfunc_idx); if (sv == NULL) goto theend; allocate_if_null(sv->sv_tv); if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(sv->sv_tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } break; \/\/ load s: variable in old script case ISN_LOADS: { hashtab_T *ht = &SCRIPT_VARS( iptr->isn_arg.loadstore.ls_sid); char_u *name = iptr->isn_arg.loadstore.ls_name; dictitem_T *di = find_var_in_ht(ht, 0, name, TRUE); if (di == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_undefined_variable_str), name); goto on_error; } else { if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(&di->di_tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } } break; \/\/ load g:\/b:\/w:\/t: variable case ISN_LOADG: case ISN_LOADB: case ISN_LOADW: case ISN_LOADT: { dictitem_T *di = NULL; hashtab_T *ht = NULL; char namespace; switch (iptr->isn_type) { case ISN_LOADG: ht = get_globvar_ht(); namespace = 'g'; break; case ISN_LOADB: ht = &curbuf->b_vars->dv_hashtab; namespace = 'b'; break; case ISN_LOADW: ht = &curwin->w_vars->dv_hashtab; namespace = 'w'; break; case ISN_LOADT: ht = &curtab->tp_vars->dv_hashtab; namespace = 't'; break; default: \/\/ Cannot reach here goto theend; } di = find_var_in_ht(ht, 0, iptr->isn_arg.string, TRUE); if (di == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_undefined_variable_char_str), namespace, iptr->isn_arg.string); goto on_error; } else { if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(&di->di_tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } } break; \/\/ load autoload variable case ISN_LOADAUTO: { char_u *name = iptr->isn_arg.string; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; SOURCING_LNUM = iptr->isn_lnum; if (eval_variable(name, (int)STRLEN(name), 0, STACK_TV_BOT(0), NULL, EVAL_VAR_VERBOSE) == FAIL) goto on_error; ++ectx->ec_stack.ga_len; } break; \/\/ load g:\/b:\/w:\/t: namespace case ISN_LOADGDICT: case ISN_LOADBDICT: case ISN_LOADWDICT: case ISN_LOADTDICT: { dict_T *d = NULL; switch (iptr->isn_type) { case ISN_LOADGDICT: d = get_globvar_dict(); break; case ISN_LOADBDICT: d = curbuf->b_vars; break; case ISN_LOADWDICT: d = curwin->w_vars; break; case ISN_LOADTDICT: d = curtab->tp_vars; break; default: \/\/ Cannot reach here goto theend; } if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->v_type = VAR_DICT; tv->v_lock = 0; tv->vval.v_dict = d; ++d->dv_refcount; ++ectx->ec_stack.ga_len; } break; \/\/ load &option case ISN_LOADOPT: { typval_T optval; char_u *name = iptr->isn_arg.string; \/\/ This is not expected to fail, name is checked during \/\/ compilation: don't set SOURCING_LNUM. if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; if (eval_option(&name, &optval, TRUE) == FAIL) goto theend; *STACK_TV_BOT(0) = optval; ++ectx->ec_stack.ga_len; } break; \/\/ load $ENV case ISN_LOADENV: { typval_T optval; char_u *name = iptr->isn_arg.string; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; \/\/ name is always valid, checked when compiling (void)eval_env_var(&name, &optval, TRUE); *STACK_TV_BOT(0) = optval; ++ectx->ec_stack.ga_len; } break; \/\/ load @register case ISN_LOADREG: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->v_type = VAR_STRING; tv->v_lock = 0; \/\/ This may result in NULL, which should be equivalent to an \/\/ empty string. tv->vval.v_string = get_reg_contents( iptr->isn_arg.number, GREG_EXPR_SRC); ++ectx->ec_stack.ga_len; break; \/\/ store local variable case ISN_STORE: --ectx->ec_stack.ga_len; tv = STACK_TV_VAR(iptr->isn_arg.number); clear_tv(tv); *tv = *STACK_TV_BOT(0); break; \/\/ store s: variable in old script case ISN_STORES: { hashtab_T *ht = &SCRIPT_VARS( iptr->isn_arg.loadstore.ls_sid); char_u *name = iptr->isn_arg.loadstore.ls_name; dictitem_T *di = find_var_in_ht(ht, 0, name + 2, TRUE); --ectx->ec_stack.ga_len; if (di == NULL) store_var(name, STACK_TV_BOT(0)); else { SOURCING_LNUM = iptr->isn_lnum; if (var_check_permission(di, name) == FAIL) { clear_tv(STACK_TV_BOT(0)); goto on_error; } clear_tv(&di->di_tv); di->di_tv = *STACK_TV_BOT(0); } } break; \/\/ store script-local variable in Vim9 script case ISN_STORESCRIPT: { scriptref_T *sref = iptr->isn_arg.script.scriptref; svar_T *sv; sv = get_script_svar(sref, ectx->ec_dfunc_idx); if (sv == NULL) goto theend; --ectx->ec_stack.ga_len; \/\/ \"const\" and \"final\" are checked at compile time, locking \/\/ the value needs to be checked here. SOURCING_LNUM = iptr->isn_lnum; if (value_check_lock(sv->sv_tv->v_lock, sv->sv_name, FALSE)) { clear_tv(STACK_TV_BOT(0)); goto on_error; } clear_tv(sv->sv_tv); *sv->sv_tv = *STACK_TV_BOT(0); } break; \/\/ store option case ISN_STOREOPT: case ISN_STOREFUNCOPT: { char_u *opt_name = iptr->isn_arg.storeopt.so_name; int opt_flags = iptr->isn_arg.storeopt.so_flags; long n = 0; char_u *s = NULL; char *msg; char_u numbuf[NUMBUFLEN]; char_u *tofree = NULL; --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); if (tv->v_type == VAR_STRING) { s = tv->vval.v_string; if (s == NULL) s = (char_u *)\"\"; } else if (iptr->isn_type == ISN_STOREFUNCOPT) { SOURCING_LNUM = iptr->isn_lnum; \/\/ If the option can be set to a function reference or \/\/ a lambda and the passed value is a function \/\/ reference, then convert it to the name (string) of \/\/ the function reference. s = tv2string(tv, &tofree, numbuf, 0); if (s == NULL || *s == NUL) { clear_tv(tv); goto on_error; } } else \/\/ must be VAR_NUMBER, CHECKTYPE makes sure n = tv->vval.v_number; msg = set_option_value(opt_name, n, s, opt_flags); clear_tv(tv); vim_free(tofree); if (msg != NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(msg)); goto on_error; } } break; \/\/ store $ENV case ISN_STOREENV: --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); vim_setenv_ext(iptr->isn_arg.string, tv_get_string(tv)); clear_tv(tv); break; \/\/ store @r case ISN_STOREREG: { int reg = iptr->isn_arg.number; --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); write_reg_contents(reg, tv_get_string(tv), -1, FALSE); clear_tv(tv); } break; \/\/ store v: variable case ISN_STOREV: --ectx->ec_stack.ga_len; if (set_vim_var_tv(iptr->isn_arg.number, STACK_TV_BOT(0)) == FAIL) \/\/ should not happen, type is checked when compiling goto on_error; break; \/\/ store g:\/b:\/w:\/t: variable case ISN_STOREG: case ISN_STOREB: case ISN_STOREW: case ISN_STORET: { dictitem_T *di; hashtab_T *ht; char_u *name = iptr->isn_arg.string + 2; switch (iptr->isn_type) { case ISN_STOREG: ht = get_globvar_ht(); break; case ISN_STOREB: ht = &curbuf->b_vars->dv_hashtab; break; case ISN_STOREW: ht = &curwin->w_vars->dv_hashtab; break; case ISN_STORET: ht = &curtab->tp_vars->dv_hashtab; break; default: \/\/ Cannot reach here goto theend; } --ectx->ec_stack.ga_len; di = find_var_in_ht(ht, 0, name, TRUE); if (di == NULL) store_var(iptr->isn_arg.string, STACK_TV_BOT(0)); else { SOURCING_LNUM = iptr->isn_lnum; if (var_check_permission(di, name) == FAIL) goto on_error; clear_tv(&di->di_tv); di->di_tv = *STACK_TV_BOT(0); } } break; \/\/ store an autoload variable case ISN_STOREAUTO: SOURCING_LNUM = iptr->isn_lnum; set_var(iptr->isn_arg.string, STACK_TV_BOT(-1), TRUE); clear_tv(STACK_TV_BOT(-1)); --ectx->ec_stack.ga_len; break; \/\/ store number in local variable case ISN_STORENR: tv = STACK_TV_VAR(iptr->isn_arg.storenr.stnr_idx); clear_tv(tv); tv->v_type = VAR_NUMBER; tv->vval.v_number = iptr->isn_arg.storenr.stnr_val; break; \/\/ store value in list or dict variable case ISN_STOREINDEX: { vartype_T dest_type = iptr->isn_arg.vartype; typval_T *tv_idx = STACK_TV_BOT(-2); typval_T *tv_dest = STACK_TV_BOT(-1); int status = OK; \/\/ Stack contains: \/\/ -3 value to be stored \/\/ -2 index \/\/ -1 dict or list tv = STACK_TV_BOT(-3); SOURCING_LNUM = iptr->isn_lnum; if (dest_type == VAR_ANY) { dest_type = tv_dest->v_type; if (dest_type == VAR_DICT) status = do_2string(tv_idx, TRUE, FALSE); else if (dest_type == VAR_LIST && tv_idx->v_type != VAR_NUMBER) { emsg(_(e_number_expected)); status = FAIL; } } else if (dest_type != tv_dest->v_type) { \/\/ just in case, should be OK semsg(_(e_expected_str_but_got_str), vartype_name(dest_type), vartype_name(tv_dest->v_type)); status = FAIL; } if (status == OK && dest_type == VAR_LIST) { long lidx = (long)tv_idx->vval.v_number; list_T *list = tv_dest->vval.v_list; if (list == NULL) { emsg(_(e_list_not_set)); goto on_error; } if (lidx < 0 && list->lv_len + lidx >= 0) \/\/ negative index is relative to the end lidx = list->lv_len + lidx; if (lidx < 0 || lidx > list->lv_len) { semsg(_(e_list_index_out_of_range_nr), lidx); goto on_error; } if (lidx < list->lv_len) { listitem_T *li = list_find(list, lidx); if (error_if_locked(li->li_tv.v_lock, e_cannot_change_list_item)) goto on_error; \/\/ overwrite existing list item clear_tv(&li->li_tv); li->li_tv = *tv; } else { if (error_if_locked(list->lv_lock, e_cannot_change_list)) goto on_error; \/\/ append to list, only fails when out of memory if (list_append_tv(list, tv) == FAIL) goto theend; clear_tv(tv); } } else if (status == OK && dest_type == VAR_DICT) { char_u *key = tv_idx->vval.v_string; dict_T *dict = tv_dest->vval.v_dict; dictitem_T *di; SOURCING_LNUM = iptr->isn_lnum; if (dict == NULL) { emsg(_(e_dictionary_not_set)); goto on_error; } if (key == NULL) key = (char_u *)\"\"; di = dict_find(dict, key, -1); if (di != NULL) { if (error_if_locked(di->di_tv.v_lock, e_cannot_change_dict_item)) goto on_error; \/\/ overwrite existing value clear_tv(&di->di_tv); di->di_tv = *tv; } else { if (error_if_locked(dict->dv_lock, e_cannot_change_dict)) goto on_error; \/\/ add to dict, only fails when out of memory if (dict_add_tv(dict, (char *)key, tv) == FAIL) goto theend; clear_tv(tv); } } else if (status == OK && dest_type == VAR_BLOB) { long lidx = (long)tv_idx->vval.v_number; blob_T *blob = tv_dest->vval.v_blob; varnumber_T nr; int error = FALSE; int len; if (blob == NULL) { emsg(_(e_blob_not_set)); goto on_error; } len = blob_len(blob); if (lidx < 0 && len + lidx >= 0) \/\/ negative index is relative to the end lidx = len + lidx; \/\/ Can add one byte at the end. if (lidx < 0 || lidx > len) { semsg(_(e_blob_index_out_of_range_nr), lidx); goto on_error; } if (value_check_lock(blob->bv_lock, (char_u *)\"blob\", FALSE)) goto on_error; nr = tv_get_number_chk(tv, &error); if (error) goto on_error; blob_set_append(blob, lidx, nr); } else { status = FAIL; semsg(_(e_cannot_index_str), vartype_name(dest_type)); } clear_tv(tv_idx); clear_tv(tv_dest); ectx->ec_stack.ga_len -= 3; if (status == FAIL) { clear_tv(tv); goto on_error; } } break; \/\/ store value in blob range case ISN_STORERANGE: { typval_T *tv_idx1 = STACK_TV_BOT(-3); typval_T *tv_idx2 = STACK_TV_BOT(-2); typval_T *tv_dest = STACK_TV_BOT(-1); int status = OK; \/\/ Stack contains: \/\/ -4 value to be stored \/\/ -3 first index or \"none\" \/\/ -2 second index or \"none\" \/\/ -1 destination list or blob tv = STACK_TV_BOT(-4); if (tv_dest->v_type == VAR_LIST) { long n1; long n2; int error = FALSE; SOURCING_LNUM = iptr->isn_lnum; n1 = (long)tv_get_number_chk(tv_idx1, &error); if (error) status = FAIL; else { if (tv_idx2->v_type == VAR_SPECIAL && tv_idx2->vval.v_number == VVAL_NONE) n2 = list_len(tv_dest->vval.v_list) - 1; else n2 = (long)tv_get_number_chk(tv_idx2, &error); if (error) status = FAIL; else { listitem_T *li1 = check_range_index_one( tv_dest->vval.v_list, &n1, FALSE); if (li1 == NULL) status = FAIL; else { status = check_range_index_two( tv_dest->vval.v_list, &n1, li1, &n2, FALSE); if (status != FAIL) status = list_assign_range( tv_dest->vval.v_list, tv->vval.v_list, n1, n2, tv_idx2->v_type == VAR_SPECIAL, (char_u *)\"=\", (char_u *)\"[unknown]\"); } } } } else if (tv_dest->v_type == VAR_BLOB) { varnumber_T n1; varnumber_T n2; int error = FALSE; n1 = tv_get_number_chk(tv_idx1, &error); if (error) status = FAIL; else { if (tv_idx2->v_type == VAR_SPECIAL && tv_idx2->vval.v_number == VVAL_NONE) n2 = blob_len(tv_dest->vval.v_blob) - 1; else n2 = tv_get_number_chk(tv_idx2, &error); if (error) status = FAIL; else { long bloblen = blob_len(tv_dest->vval.v_blob); if (check_blob_index(bloblen, n1, FALSE) == FAIL || check_blob_range(bloblen, n1, n2, FALSE) == FAIL) status = FAIL; else status = blob_set_range( tv_dest->vval.v_blob, n1, n2, tv); } } } else { status = FAIL; emsg(_(e_blob_required)); } clear_tv(tv_idx1); clear_tv(tv_idx2); clear_tv(tv_dest); ectx->ec_stack.ga_len -= 4; clear_tv(tv); if (status == FAIL) goto on_error; } break; \/\/ load or store variable or argument from outer scope case ISN_LOADOUTER: case ISN_STOREOUTER: { int depth = iptr->isn_arg.outer.outer_depth; outer_T *outer = ectx->ec_outer_ref == NULL ? NULL : ectx->ec_outer_ref->or_outer; while (depth > 1 && outer != NULL) { outer = outer->out_up; --depth; } if (outer == NULL) { SOURCING_LNUM = iptr->isn_lnum; if (ectx->ec_frame_idx == ectx->ec_initial_frame_idx || ectx->ec_outer_ref == NULL) \/\/ Possibly :def function called from legacy \/\/ context. emsg(_(e_closure_called_from_invalid_context)); else iemsg(\"LOADOUTER depth more than scope levels\"); goto theend; } tv = ((typval_T *)outer->out_stack->ga_data) + outer->out_frame_idx + STACK_FRAME_SIZE + iptr->isn_arg.outer.outer_idx; if (iptr->isn_type == ISN_LOADOUTER) { if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; copy_tv(tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } else { --ectx->ec_stack.ga_len; clear_tv(tv); *tv = *STACK_TV_BOT(0); } } break; \/\/ unlet item in list or dict variable case ISN_UNLETINDEX: { typval_T *tv_idx = STACK_TV_BOT(-2); typval_T *tv_dest = STACK_TV_BOT(-1); int status = OK; \/\/ Stack contains: \/\/ -2 index \/\/ -1 dict or list if (tv_dest->v_type == VAR_DICT) { \/\/ unlet a dict item, index must be a string if (tv_idx->v_type != VAR_STRING) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_expected_str_but_got_str), vartype_name(VAR_STRING), vartype_name(tv_idx->v_type)); status = FAIL; } else { dict_T *d = tv_dest->vval.v_dict; char_u *key = tv_idx->vval.v_string; dictitem_T *di = NULL; if (d != NULL && value_check_lock( d->dv_lock, NULL, FALSE)) status = FAIL; else { SOURCING_LNUM = iptr->isn_lnum; if (key == NULL) key = (char_u *)\"\"; if (d != NULL) di = dict_find(d, key, (int)STRLEN(key)); if (di == NULL) { \/\/ NULL dict is equivalent to empty dict semsg(_(e_key_not_present_in_dictionary), key); status = FAIL; } else if (var_check_fixed(di->di_flags, NULL, FALSE) || var_check_ro(di->di_flags, NULL, FALSE)) status = FAIL; else dictitem_remove(d, di); } } } else if (tv_dest->v_type == VAR_LIST) { \/\/ unlet a List item, index must be a number SOURCING_LNUM = iptr->isn_lnum; if (check_for_number(tv_idx) == FAIL) { status = FAIL; } else { list_T *l = tv_dest->vval.v_list; long n = (long)tv_idx->vval.v_number; if (l != NULL && value_check_lock( l->lv_lock, NULL, FALSE)) status = FAIL; else { listitem_T *li = list_find(l, n); if (li == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_list_index_out_of_range_nr), n); status = FAIL; } else if (value_check_lock(li->li_tv.v_lock, NULL, FALSE)) status = FAIL; else listitem_remove(l, li); } } } else { status = FAIL; semsg(_(e_cannot_index_str), vartype_name(tv_dest->v_type)); } clear_tv(tv_idx); clear_tv(tv_dest); ectx->ec_stack.ga_len -= 2; if (status == FAIL) goto on_error; } break; \/\/ unlet range of items in list variable case ISN_UNLETRANGE: { \/\/ Stack contains: \/\/ -3 index1 \/\/ -2 index2 \/\/ -1 dict or list typval_T *tv_idx1 = STACK_TV_BOT(-3); typval_T *tv_idx2 = STACK_TV_BOT(-2); typval_T *tv_dest = STACK_TV_BOT(-1); int status = OK; if (tv_dest->v_type == VAR_LIST) { \/\/ indexes must be a number SOURCING_LNUM = iptr->isn_lnum; if (check_for_number(tv_idx1) == FAIL || (tv_idx2->v_type != VAR_SPECIAL && check_for_number(tv_idx2) == FAIL)) { status = FAIL; } else { list_T *l = tv_dest->vval.v_list; long n1 = (long)tv_idx1->vval.v_number; long n2 = tv_idx2->v_type == VAR_SPECIAL ? 0 : (long)tv_idx2->vval.v_number; listitem_T *li; li = list_find_index(l, &n1); if (li == NULL) status = FAIL; else { if (n1 < 0) n1 = list_idx_of_item(l, li); if (n2 < 0) { listitem_T *li2 = list_find(l, n2); if (li2 == NULL) status = FAIL; else n2 = list_idx_of_item(l, li2); } if (status != FAIL && tv_idx2->v_type != VAR_SPECIAL && n2 < n1) { semsg(_(e_list_index_out_of_range_nr), n2); status = FAIL; } if (status != FAIL && list_unlet_range(l, li, NULL, n1, tv_idx2->v_type != VAR_SPECIAL, n2) == FAIL) status = FAIL; } } } else { status = FAIL; SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_cannot_index_str), vartype_name(tv_dest->v_type)); } clear_tv(tv_idx1); clear_tv(tv_idx2); clear_tv(tv_dest); ectx->ec_stack.ga_len -= 3; if (status == FAIL) goto on_error; } break; \/\/ push constant case ISN_PUSHNR: case ISN_PUSHBOOL: case ISN_PUSHSPEC: case ISN_PUSHF: case ISN_PUSHS: case ISN_PUSHBLOB: case ISN_PUSHFUNC: case ISN_PUSHCHANNEL: case ISN_PUSHJOB: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); tv->v_lock = 0; ++ectx->ec_stack.ga_len; switch (iptr->isn_type) { case ISN_PUSHNR: tv->v_type = VAR_NUMBER; tv->vval.v_number = iptr->isn_arg.number; break; case ISN_PUSHBOOL: tv->v_type = VAR_BOOL; tv->vval.v_number = iptr->isn_arg.number; break; case ISN_PUSHSPEC: tv->v_type = VAR_SPECIAL; tv->vval.v_number = iptr->isn_arg.number; break; #ifdef FEAT_FLOAT case ISN_PUSHF: tv->v_type = VAR_FLOAT; tv->vval.v_float = iptr->isn_arg.fnumber; break; #endif case ISN_PUSHBLOB: blob_copy(iptr->isn_arg.blob, tv); break; case ISN_PUSHFUNC: tv->v_type = VAR_FUNC; if (iptr->isn_arg.string == NULL) tv->vval.v_string = NULL; else tv->vval.v_string = vim_strsave(iptr->isn_arg.string); break; case ISN_PUSHCHANNEL: #ifdef FEAT_JOB_CHANNEL tv->v_type = VAR_CHANNEL; tv->vval.v_channel = iptr->isn_arg.channel; if (tv->vval.v_channel != NULL) ++tv->vval.v_channel->ch_refcount; #endif break; case ISN_PUSHJOB: #ifdef FEAT_JOB_CHANNEL tv->v_type = VAR_JOB; tv->vval.v_job = iptr->isn_arg.job; if (tv->vval.v_job != NULL) ++tv->vval.v_job->jv_refcount; #endif break; default: tv->v_type = VAR_STRING; tv->vval.v_string = vim_strsave( iptr->isn_arg.string == NULL ? (char_u *)\"\" : iptr->isn_arg.string); } break; case ISN_UNLET: if (do_unlet(iptr->isn_arg.unlet.ul_name, iptr->isn_arg.unlet.ul_forceit) == FAIL) goto on_error; break; case ISN_UNLETENV: vim_unsetenv(iptr->isn_arg.unlet.ul_name); break; case ISN_LOCKUNLOCK: { typval_T *lval_root_save = lval_root; int res; \/\/ Stack has the local variable, argument the whole :lock \/\/ or :unlock command, like ISN_EXEC. --ectx->ec_stack.ga_len; lval_root = STACK_TV_BOT(0); res = exec_command(iptr); clear_tv(lval_root); lval_root = lval_root_save; if (res == FAIL) goto on_error; } break; case ISN_LOCKCONST: item_lock(STACK_TV_BOT(-1), 100, TRUE, TRUE); break; \/\/ create a list from items on the stack; uses a single allocation \/\/ for the list header and the items case ISN_NEWLIST: if (exe_newlist(iptr->isn_arg.number, ectx) == FAIL) goto theend; break; \/\/ create a dict from items on the stack case ISN_NEWDICT: { int count = iptr->isn_arg.number; dict_T *dict = dict_alloc(); dictitem_T *item; char_u *key; int idx; if (unlikely(dict == NULL)) goto theend; for (idx = 0; idx < count; ++idx) { \/\/ have already checked key type is VAR_STRING tv = STACK_TV_BOT(2 * (idx - count)); \/\/ check key is unique key = tv->vval.v_string == NULL ? (char_u *)\"\" : tv->vval.v_string; item = dict_find(dict, key, -1); if (item != NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_duplicate_key_in_dicitonary), key); dict_unref(dict); goto on_error; } item = dictitem_alloc(key); clear_tv(tv); if (unlikely(item == NULL)) { dict_unref(dict); goto theend; } item->di_tv = *STACK_TV_BOT(2 * (idx - count) + 1); item->di_tv.v_lock = 0; if (dict_add(dict, item) == FAIL) { \/\/ can this ever happen? dict_unref(dict); goto theend; } } if (count > 0) ectx->ec_stack.ga_len -= 2 * count - 1; else if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; else ++ectx->ec_stack.ga_len; tv = STACK_TV_BOT(-1); tv->v_type = VAR_DICT; tv->v_lock = 0; tv->vval.v_dict = dict; ++dict->dv_refcount; } break; \/\/ call a :def function case ISN_DCALL: SOURCING_LNUM = iptr->isn_lnum; if (call_dfunc(iptr->isn_arg.dfunc.cdf_idx, NULL, iptr->isn_arg.dfunc.cdf_argcount, ectx) == FAIL) goto on_error; break; \/\/ call a builtin function case ISN_BCALL: SOURCING_LNUM = iptr->isn_lnum; if (call_bfunc(iptr->isn_arg.bfunc.cbf_idx, iptr->isn_arg.bfunc.cbf_argcount, ectx) == FAIL) goto on_error; break; \/\/ call a funcref or partial case ISN_PCALL: { cpfunc_T *pfunc = &iptr->isn_arg.pfunc; int r; typval_T partial_tv; SOURCING_LNUM = iptr->isn_lnum; if (pfunc->cpf_top) { \/\/ funcref is above the arguments tv = STACK_TV_BOT(-pfunc->cpf_argcount - 1); } else { \/\/ Get the funcref from the stack. --ectx->ec_stack.ga_len; partial_tv = *STACK_TV_BOT(0); tv = &partial_tv; } r = call_partial(tv, pfunc->cpf_argcount, ectx); if (tv == &partial_tv) clear_tv(&partial_tv); if (r == FAIL) goto on_error; } break; case ISN_PCALL_END: \/\/ PCALL finished, arguments have been consumed and replaced by \/\/ the return value. Now clear the funcref from the stack, \/\/ and move the return value in its place. --ectx->ec_stack.ga_len; clear_tv(STACK_TV_BOT(-1)); *STACK_TV_BOT(-1) = *STACK_TV_BOT(0); break; \/\/ call a user defined function or funcref\/partial case ISN_UCALL: { cufunc_T *cufunc = &iptr->isn_arg.ufunc; SOURCING_LNUM = iptr->isn_lnum; if (call_eval_func(cufunc->cuf_name, cufunc->cuf_argcount, ectx, iptr) == FAIL) goto on_error; } break; \/\/ return from a :def function call without a value case ISN_RETURN_VOID: if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); ++ectx->ec_stack.ga_len; tv->v_type = VAR_VOID; tv->vval.v_number = 0; tv->v_lock = 0; \/\/ FALLTHROUGH \/\/ return from a :def function call with what is on the stack case ISN_RETURN: { garray_T *trystack = &ectx->ec_trystack; trycmd_T *trycmd = NULL; if (trystack->ga_len > 0) trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - 1; if (trycmd != NULL && trycmd->tcd_frame_idx == ectx->ec_frame_idx) { \/\/ jump to \":finally\" or \":endtry\" if (trycmd->tcd_finally_idx != 0) ectx->ec_iidx = trycmd->tcd_finally_idx; else ectx->ec_iidx = trycmd->tcd_endtry_idx; trycmd->tcd_return = TRUE; } else goto func_return; } break; \/\/ push a partial, a reference to a compiled function case ISN_FUNCREF: { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); ufunc_T *ufunc; funcref_T *funcref = &iptr->isn_arg.funcref; if (pt == NULL) goto theend; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) { vim_free(pt); goto theend; } if (funcref->fr_func_name == NULL) { dfunc_T *pt_dfunc = ((dfunc_T *)def_functions.ga_data) + funcref->fr_dfunc_idx; ufunc = pt_dfunc->df_ufunc; } else { ufunc = find_func(funcref->fr_func_name, FALSE, NULL); } if (ufunc == NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_function_reference_invalid)); goto theend; } if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) goto theend; tv = STACK_TV_BOT(0); ++ectx->ec_stack.ga_len; tv->vval.v_partial = pt; tv->v_type = VAR_PARTIAL; tv->v_lock = 0; } break; \/\/ Create a global function from a lambda. case ISN_NEWFUNC: { newfunc_T *newfunc = &iptr->isn_arg.newfunc; if (copy_func(newfunc->nf_lambda, newfunc->nf_global, ectx) == FAIL) goto theend; } break; \/\/ List functions case ISN_DEF: if (iptr->isn_arg.string == NULL) list_functions(NULL); else { exarg_T ea; char_u *line_to_free = NULL; CLEAR_FIELD(ea); ea.cmd = ea.arg = iptr->isn_arg.string; define_function(&ea, NULL, &line_to_free); vim_free(line_to_free); } break; \/\/ jump if a condition is met case ISN_JUMP: { jumpwhen_T when = iptr->isn_arg.jump.jump_when; int error = FALSE; int jump = TRUE; if (when != JUMP_ALWAYS) { tv = STACK_TV_BOT(-1); if (when == JUMP_IF_COND_FALSE || when == JUMP_IF_FALSE || when == JUMP_IF_COND_TRUE) { SOURCING_LNUM = iptr->isn_lnum; jump = tv_get_bool_chk(tv, &error); if (error) goto on_error; } else jump = tv2bool(tv); if (when == JUMP_IF_FALSE || when == JUMP_AND_KEEP_IF_FALSE || when == JUMP_IF_COND_FALSE) jump = !jump; if (when == JUMP_IF_FALSE || !jump) { \/\/ drop the value from the stack clear_tv(tv); --ectx->ec_stack.ga_len; } } if (jump) ectx->ec_iidx = iptr->isn_arg.jump.jump_where; } break; \/\/ Jump if an argument with a default value was already set and not \/\/ v:none. case ISN_JUMP_IF_ARG_SET: tv = STACK_TV_VAR(iptr->isn_arg.jumparg.jump_arg_off); if (tv->v_type != VAR_UNKNOWN && !(tv->v_type == VAR_SPECIAL && tv->vval.v_number == VVAL_NONE)) ectx->ec_iidx = iptr->isn_arg.jumparg.jump_where; break; \/\/ top of a for loop case ISN_FOR: { typval_T *ltv = STACK_TV_BOT(-1); typval_T *idxtv = STACK_TV_VAR(iptr->isn_arg.forloop.for_idx); if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; if (ltv->v_type == VAR_LIST) { list_T *list = ltv->vval.v_list; \/\/ push the next item from the list ++idxtv->vval.v_number; if (list == NULL || idxtv->vval.v_number >= list->lv_len) { \/\/ past the end of the list, jump to \"endfor\" ectx->ec_iidx = iptr->isn_arg.forloop.for_end; may_restore_cmdmod(&ectx->ec_funclocal); } else if (list->lv_first == &range_list_item) { \/\/ non-materialized range() list tv = STACK_TV_BOT(0); tv->v_type = VAR_NUMBER; tv->v_lock = 0; tv->vval.v_number = list_find_nr( list, idxtv->vval.v_number, NULL); ++ectx->ec_stack.ga_len; } else { listitem_T *li = list_find(list, idxtv->vval.v_number); copy_tv(&li->li_tv, STACK_TV_BOT(0)); ++ectx->ec_stack.ga_len; } } else if (ltv->v_type == VAR_STRING) { char_u *str = ltv->vval.v_string; \/\/ The index is for the last byte of the previous \/\/ character. ++idxtv->vval.v_number; if (str == NULL || str[idxtv->vval.v_number] == NUL) { \/\/ past the end of the string, jump to \"endfor\" ectx->ec_iidx = iptr->isn_arg.forloop.for_end; may_restore_cmdmod(&ectx->ec_funclocal); } else { int clen = mb_ptr2len(str + idxtv->vval.v_number); \/\/ Push the next character from the string. tv = STACK_TV_BOT(0); tv->v_type = VAR_STRING; tv->vval.v_string = vim_strnsave( str + idxtv->vval.v_number, clen); ++ectx->ec_stack.ga_len; idxtv->vval.v_number += clen - 1; } } else if (ltv->v_type == VAR_BLOB) { blob_T *blob = ltv->vval.v_blob; \/\/ When we get here the first time make a copy of the \/\/ blob, so that the iteration still works when it is \/\/ changed. if (idxtv->vval.v_number == -1 && blob != NULL) { blob_copy(blob, ltv); blob_unref(blob); blob = ltv->vval.v_blob; } \/\/ The index is for the previous byte. ++idxtv->vval.v_number; if (blob == NULL || idxtv->vval.v_number >= blob_len(blob)) { \/\/ past the end of the blob, jump to \"endfor\" ectx->ec_iidx = iptr->isn_arg.forloop.for_end; may_restore_cmdmod(&ectx->ec_funclocal); } else { \/\/ Push the next byte from the blob. tv = STACK_TV_BOT(0); tv->v_type = VAR_NUMBER; tv->vval.v_number = blob_get(blob, idxtv->vval.v_number); ++ectx->ec_stack.ga_len; } } else { semsg(_(e_for_loop_on_str_not_supported), vartype_name(ltv->v_type)); goto theend; } } break; \/\/ start of \":try\" block case ISN_TRY: { trycmd_T *trycmd = NULL; if (GA_GROW_FAILS(&ectx->ec_trystack, 1)) goto theend; trycmd = ((trycmd_T *)ectx->ec_trystack.ga_data) + ectx->ec_trystack.ga_len; ++ectx->ec_trystack.ga_len; ++trylevel; CLEAR_POINTER(trycmd); trycmd->tcd_frame_idx = ectx->ec_frame_idx; trycmd->tcd_stack_len = ectx->ec_stack.ga_len; trycmd->tcd_catch_idx = iptr->isn_arg.tryref.try_ref->try_catch; trycmd->tcd_finally_idx = iptr->isn_arg.tryref.try_ref->try_finally; trycmd->tcd_endtry_idx = iptr->isn_arg.tryref.try_ref->try_endtry; } break; case ISN_PUSHEXC: if (current_exception == NULL) { SOURCING_LNUM = iptr->isn_lnum; iemsg(\"Evaluating catch while current_exception is NULL\"); goto theend; } if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; tv = STACK_TV_BOT(0); ++ectx->ec_stack.ga_len; tv->v_type = VAR_STRING; tv->v_lock = 0; tv->vval.v_string = vim_strsave( (char_u *)current_exception->value); break; case ISN_CATCH: { garray_T *trystack = &ectx->ec_trystack; may_restore_cmdmod(&ectx->ec_funclocal); if (trystack->ga_len > 0) { trycmd_T *trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - 1; trycmd->tcd_caught = TRUE; trycmd->tcd_did_throw = FALSE; } did_emsg = got_int = did_throw = FALSE; force_abort = need_rethrow = FALSE; catch_exception(current_exception); } break; case ISN_TRYCONT: { garray_T *trystack = &ectx->ec_trystack; trycont_T *trycont = &iptr->isn_arg.trycont; int i; trycmd_T *trycmd; int iidx = trycont->tct_where; if (trystack->ga_len < trycont->tct_levels) { siemsg(\"TRYCONT: expected %d levels, found %d\", trycont->tct_levels, trystack->ga_len); goto theend; } \/\/ Make :endtry jump to any outer try block and the last \/\/ :endtry inside the loop to the loop start. for (i = trycont->tct_levels; i > 0; --i) { trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - i; \/\/ Add one to tcd_cont to be able to jump to \/\/ instruction with index zero. trycmd->tcd_cont = iidx + 1; iidx = trycmd->tcd_finally_idx == 0 ? trycmd->tcd_endtry_idx : trycmd->tcd_finally_idx; } \/\/ jump to :finally or :endtry of current try statement ectx->ec_iidx = iidx; } break; case ISN_FINALLY: { garray_T *trystack = &ectx->ec_trystack; trycmd_T *trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - 1; \/\/ Reset the index to avoid a return statement jumps here \/\/ again. trycmd->tcd_finally_idx = 0; break; } \/\/ end of \":try\" block case ISN_ENDTRY: { garray_T *trystack = &ectx->ec_trystack; if (trystack->ga_len > 0) { trycmd_T *trycmd; --trystack->ga_len; --trylevel; trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len; if (trycmd->tcd_did_throw) did_throw = TRUE; if (trycmd->tcd_caught && current_exception != NULL) { \/\/ discard the exception if (caught_stack == current_exception) caught_stack = caught_stack->caught; discard_current_exception(); } if (trycmd->tcd_return) goto func_return; while (ectx->ec_stack.ga_len > trycmd->tcd_stack_len) { --ectx->ec_stack.ga_len; clear_tv(STACK_TV_BOT(0)); } if (trycmd->tcd_cont != 0) \/\/ handling :continue: jump to outer try block or \/\/ start of the loop ectx->ec_iidx = trycmd->tcd_cont - 1; } } break; case ISN_THROW: { garray_T *trystack = &ectx->ec_trystack; if (trystack->ga_len == 0 && trylevel == 0 && emsg_silent) { \/\/ throwing an exception while using \"silent!\" causes \/\/ the function to abort but not display an error. tv = STACK_TV_BOT(-1); clear_tv(tv); tv->v_type = VAR_NUMBER; tv->vval.v_number = 0; goto done; } --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(0); if (tv->vval.v_string == NULL || *skipwhite(tv->vval.v_string) == NUL) { vim_free(tv->vval.v_string); SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_throw_with_empty_string)); goto theend; } \/\/ Inside a \"catch\" we need to first discard the caught \/\/ exception. if (trystack->ga_len > 0) { trycmd_T *trycmd = ((trycmd_T *)trystack->ga_data) + trystack->ga_len - 1; if (trycmd->tcd_caught && current_exception != NULL) { \/\/ discard the exception if (caught_stack == current_exception) caught_stack = caught_stack->caught; discard_current_exception(); trycmd->tcd_caught = FALSE; } } if (throw_exception(tv->vval.v_string, ET_USER, NULL) == FAIL) { vim_free(tv->vval.v_string); goto theend; } did_throw = TRUE; } break; \/\/ compare with special values case ISN_COMPAREBOOL: case ISN_COMPARESPECIAL: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); varnumber_T arg1 = tv1->vval.v_number; varnumber_T arg2 = tv2->vval.v_number; int res; switch (iptr->isn_arg.op.op_type) { case EXPR_EQUAL: res = arg1 == arg2; break; case EXPR_NEQUAL: res = arg1 != arg2; break; default: res = 0; break; } --ectx->ec_stack.ga_len; tv1->v_type = VAR_BOOL; tv1->vval.v_number = res ? VVAL_TRUE : VVAL_FALSE; } break; \/\/ Operation with two number arguments case ISN_OPNR: case ISN_COMPARENR: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); varnumber_T arg1 = tv1->vval.v_number; varnumber_T arg2 = tv2->vval.v_number; varnumber_T res = 0; int div_zero = FALSE; switch (iptr->isn_arg.op.op_type) { case EXPR_MULT: res = arg1 * arg2; break; case EXPR_DIV: if (arg2 == 0) div_zero = TRUE; else res = arg1 \/ arg2; break; case EXPR_REM: if (arg2 == 0) div_zero = TRUE; else res = arg1 % arg2; break; case EXPR_SUB: res = arg1 - arg2; break; case EXPR_ADD: res = arg1 + arg2; break; case EXPR_EQUAL: res = arg1 == arg2; break; case EXPR_NEQUAL: res = arg1 != arg2; break; case EXPR_GREATER: res = arg1 > arg2; break; case EXPR_GEQUAL: res = arg1 >= arg2; break; case EXPR_SMALLER: res = arg1 < arg2; break; case EXPR_SEQUAL: res = arg1 <= arg2; break; default: break; } --ectx->ec_stack.ga_len; if (iptr->isn_type == ISN_COMPARENR) { tv1->v_type = VAR_BOOL; tv1->vval.v_number = res ? VVAL_TRUE : VVAL_FALSE; } else tv1->vval.v_number = res; if (div_zero) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_divide_by_zero)); goto on_error; } } break; \/\/ Computation with two float arguments case ISN_OPFLOAT: case ISN_COMPAREFLOAT: #ifdef FEAT_FLOAT { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); float_T arg1 = tv1->vval.v_float; float_T arg2 = tv2->vval.v_float; float_T res = 0; int cmp = FALSE; switch (iptr->isn_arg.op.op_type) { case EXPR_MULT: res = arg1 * arg2; break; case EXPR_DIV: res = arg1 \/ arg2; break; case EXPR_SUB: res = arg1 - arg2; break; case EXPR_ADD: res = arg1 + arg2; break; case EXPR_EQUAL: cmp = arg1 == arg2; break; case EXPR_NEQUAL: cmp = arg1 != arg2; break; case EXPR_GREATER: cmp = arg1 > arg2; break; case EXPR_GEQUAL: cmp = arg1 >= arg2; break; case EXPR_SMALLER: cmp = arg1 < arg2; break; case EXPR_SEQUAL: cmp = arg1 <= arg2; break; default: cmp = 0; break; } --ectx->ec_stack.ga_len; if (iptr->isn_type == ISN_COMPAREFLOAT) { tv1->v_type = VAR_BOOL; tv1->vval.v_number = cmp ? VVAL_TRUE : VVAL_FALSE; } else tv1->vval.v_float = res; } #endif break; case ISN_COMPARELIST: case ISN_COMPAREDICT: case ISN_COMPAREFUNC: case ISN_COMPARESTRING: case ISN_COMPAREBLOB: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); exprtype_T exprtype = iptr->isn_arg.op.op_type; int ic = iptr->isn_arg.op.op_ic; int res = FALSE; int status = OK; SOURCING_LNUM = iptr->isn_lnum; if (iptr->isn_type == ISN_COMPARELIST) { status = typval_compare_list(tv1, tv2, exprtype, ic, &res); } else if (iptr->isn_type == ISN_COMPAREDICT) { status = typval_compare_dict(tv1, tv2, exprtype, ic, &res); } else if (iptr->isn_type == ISN_COMPAREFUNC) { status = typval_compare_func(tv1, tv2, exprtype, ic, &res); } else if (iptr->isn_type == ISN_COMPARESTRING) { status = typval_compare_string(tv1, tv2, exprtype, ic, &res); } else { status = typval_compare_blob(tv1, tv2, exprtype, &res); } --ectx->ec_stack.ga_len; clear_tv(tv1); clear_tv(tv2); tv1->v_type = VAR_BOOL; tv1->vval.v_number = res ? VVAL_TRUE : VVAL_FALSE; if (status == FAIL) goto theend; } break; case ISN_COMPAREANY: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); exprtype_T exprtype = iptr->isn_arg.op.op_type; int ic = iptr->isn_arg.op.op_ic; int status; SOURCING_LNUM = iptr->isn_lnum; status = typval_compare(tv1, tv2, exprtype, ic); clear_tv(tv2); --ectx->ec_stack.ga_len; if (status == FAIL) goto theend; } break; case ISN_ADDLIST: case ISN_ADDBLOB: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); \/\/ add two lists or blobs if (iptr->isn_type == ISN_ADDLIST) { if (iptr->isn_arg.op.op_type == EXPR_APPEND && tv1->vval.v_list != NULL) list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL); else eval_addlist(tv1, tv2); } else eval_addblob(tv1, tv2); clear_tv(tv2); --ectx->ec_stack.ga_len; } break; case ISN_LISTAPPEND: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); list_T *l = tv1->vval.v_list; \/\/ add an item to a list SOURCING_LNUM = iptr->isn_lnum; if (l == NULL) { emsg(_(e_cannot_add_to_null_list)); goto on_error; } if (value_check_lock(l->lv_lock, NULL, FALSE)) goto on_error; if (list_append_tv(l, tv2) == FAIL) goto theend; clear_tv(tv2); --ectx->ec_stack.ga_len; } break; case ISN_BLOBAPPEND: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); blob_T *b = tv1->vval.v_blob; int error = FALSE; varnumber_T n; \/\/ add a number to a blob if (b == NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_cannot_add_to_null_blob)); goto on_error; } n = tv_get_number_chk(tv2, &error); if (error) goto on_error; ga_append(&b->bv_ga, (int)n); --ectx->ec_stack.ga_len; } break; \/\/ Computation with two arguments of unknown type case ISN_OPANY: { typval_T *tv1 = STACK_TV_BOT(-2); typval_T *tv2 = STACK_TV_BOT(-1); varnumber_T n1, n2; #ifdef FEAT_FLOAT float_T f1 = 0, f2 = 0; #endif int error = FALSE; if (iptr->isn_arg.op.op_type == EXPR_ADD) { if (tv1->v_type == VAR_LIST && tv2->v_type == VAR_LIST) { eval_addlist(tv1, tv2); clear_tv(tv2); --ectx->ec_stack.ga_len; break; } else if (tv1->v_type == VAR_BLOB && tv2->v_type == VAR_BLOB) { eval_addblob(tv1, tv2); clear_tv(tv2); --ectx->ec_stack.ga_len; break; } } #ifdef FEAT_FLOAT if (tv1->v_type == VAR_FLOAT) { f1 = tv1->vval.v_float; n1 = 0; } else #endif { SOURCING_LNUM = iptr->isn_lnum; n1 = tv_get_number_chk(tv1, &error); if (error) goto on_error; #ifdef FEAT_FLOAT if (tv2->v_type == VAR_FLOAT) f1 = n1; #endif } #ifdef FEAT_FLOAT if (tv2->v_type == VAR_FLOAT) { f2 = tv2->vval.v_float; n2 = 0; } else #endif { n2 = tv_get_number_chk(tv2, &error); if (error) goto on_error; #ifdef FEAT_FLOAT if (tv1->v_type == VAR_FLOAT) f2 = n2; #endif } #ifdef FEAT_FLOAT \/\/ if there is a float on either side the result is a float if (tv1->v_type == VAR_FLOAT || tv2->v_type == VAR_FLOAT) { switch (iptr->isn_arg.op.op_type) { case EXPR_MULT: f1 = f1 * f2; break; case EXPR_DIV: f1 = f1 \/ f2; break; case EXPR_SUB: f1 = f1 - f2; break; case EXPR_ADD: f1 = f1 + f2; break; default: SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_cannot_use_percent_with_float)); goto on_error; } clear_tv(tv1); clear_tv(tv2); tv1->v_type = VAR_FLOAT; tv1->vval.v_float = f1; --ectx->ec_stack.ga_len; } else #endif { int failed = FALSE; switch (iptr->isn_arg.op.op_type) { case EXPR_MULT: n1 = n1 * n2; break; case EXPR_DIV: n1 = num_divide(n1, n2, &failed); if (failed) goto on_error; break; case EXPR_SUB: n1 = n1 - n2; break; case EXPR_ADD: n1 = n1 + n2; break; default: n1 = num_modulus(n1, n2, &failed); if (failed) goto on_error; break; } clear_tv(tv1); clear_tv(tv2); tv1->v_type = VAR_NUMBER; tv1->vval.v_number = n1; --ectx->ec_stack.ga_len; } } break; case ISN_CONCAT: { char_u *str1 = STACK_TV_BOT(-2)->vval.v_string; char_u *str2 = STACK_TV_BOT(-1)->vval.v_string; char_u *res; res = concat_str(str1, str2); clear_tv(STACK_TV_BOT(-2)); clear_tv(STACK_TV_BOT(-1)); --ectx->ec_stack.ga_len; STACK_TV_BOT(-1)->vval.v_string = res; } break; case ISN_STRINDEX: case ISN_STRSLICE: { int is_slice = iptr->isn_type == ISN_STRSLICE; varnumber_T n1 = 0, n2; char_u *res; \/\/ string index: string is at stack-2, index at stack-1 \/\/ string slice: string is at stack-3, first index at \/\/ stack-2, second index at stack-1 if (is_slice) { tv = STACK_TV_BOT(-2); n1 = tv->vval.v_number; } tv = STACK_TV_BOT(-1); n2 = tv->vval.v_number; ectx->ec_stack.ga_len -= is_slice ? 2 : 1; tv = STACK_TV_BOT(-1); if (is_slice) \/\/ Slice: Select the characters from the string res = string_slice(tv->vval.v_string, n1, n2, FALSE); else \/\/ Index: The resulting variable is a string of a \/\/ single character (including composing characters). \/\/ If the index is too big or negative the result is \/\/ empty. res = char_from_string(tv->vval.v_string, n2); vim_free(tv->vval.v_string); tv->vval.v_string = res; } break; case ISN_LISTINDEX: case ISN_LISTSLICE: case ISN_BLOBINDEX: case ISN_BLOBSLICE: { int is_slice = iptr->isn_type == ISN_LISTSLICE || iptr->isn_type == ISN_BLOBSLICE; int is_blob = iptr->isn_type == ISN_BLOBINDEX || iptr->isn_type == ISN_BLOBSLICE; varnumber_T n1, n2; typval_T *val_tv; \/\/ list index: list is at stack-2, index at stack-1 \/\/ list slice: list is at stack-3, indexes at stack-2 and \/\/ stack-1 \/\/ Same for blob. val_tv = is_slice ? STACK_TV_BOT(-3) : STACK_TV_BOT(-2); tv = STACK_TV_BOT(-1); n1 = n2 = tv->vval.v_number; clear_tv(tv); if (is_slice) { tv = STACK_TV_BOT(-2); n1 = tv->vval.v_number; clear_tv(tv); } ectx->ec_stack.ga_len -= is_slice ? 2 : 1; tv = STACK_TV_BOT(-1); SOURCING_LNUM = iptr->isn_lnum; if (is_blob) { if (blob_slice_or_index(val_tv->vval.v_blob, is_slice, n1, n2, FALSE, tv) == FAIL) goto on_error; } else { if (list_slice_or_index(val_tv->vval.v_list, is_slice, n1, n2, FALSE, tv, TRUE) == FAIL) goto on_error; } } break; case ISN_ANYINDEX: case ISN_ANYSLICE: { int is_slice = iptr->isn_type == ISN_ANYSLICE; typval_T *var1, *var2; int res; \/\/ index: composite is at stack-2, index at stack-1 \/\/ slice: composite is at stack-3, indexes at stack-2 and \/\/ stack-1 tv = is_slice ? STACK_TV_BOT(-3) : STACK_TV_BOT(-2); SOURCING_LNUM = iptr->isn_lnum; if (check_can_index(tv, TRUE, TRUE) == FAIL) goto on_error; var1 = is_slice ? STACK_TV_BOT(-2) : STACK_TV_BOT(-1); var2 = is_slice ? STACK_TV_BOT(-1) : NULL; res = eval_index_inner(tv, is_slice, var1, var2, FALSE, NULL, -1, TRUE); clear_tv(var1); if (is_slice) clear_tv(var2); ectx->ec_stack.ga_len -= is_slice ? 2 : 1; if (res == FAIL) goto on_error; } break; case ISN_SLICE: { list_T *list; int count = iptr->isn_arg.number; \/\/ type will have been checked to be a list tv = STACK_TV_BOT(-1); list = tv->vval.v_list; \/\/ no error for short list, expect it to be checked earlier if (list != NULL && list->lv_len >= count) { list_T *newlist = list_slice(list, count, list->lv_len - 1); if (newlist != NULL) { list_unref(list); tv->vval.v_list = newlist; ++newlist->lv_refcount; } } } break; case ISN_GETITEM: { listitem_T *li; getitem_T *gi = &iptr->isn_arg.getitem; \/\/ Get list item: list is at stack-1, push item. \/\/ List type and length is checked for when compiling. tv = STACK_TV_BOT(-1 - gi->gi_with_op); li = list_find(tv->vval.v_list, gi->gi_index); if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; ++ectx->ec_stack.ga_len; copy_tv(&li->li_tv, STACK_TV_BOT(-1)); \/\/ Useful when used in unpack assignment. Reset at \/\/ ISN_DROP. ectx->ec_where.wt_index = gi->gi_index + 1; ectx->ec_where.wt_variable = TRUE; } break; case ISN_MEMBER: { dict_T *dict; char_u *key; dictitem_T *di; \/\/ dict member: dict is at stack-2, key at stack-1 tv = STACK_TV_BOT(-2); \/\/ no need to check for VAR_DICT, CHECKTYPE will check. dict = tv->vval.v_dict; tv = STACK_TV_BOT(-1); \/\/ no need to check for VAR_STRING, 2STRING will check. key = tv->vval.v_string; if (key == NULL) key = (char_u *)\"\"; if ((di = dict_find(dict, key, -1)) == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_key_not_present_in_dictionary), key); \/\/ If :silent! is used we will continue, make sure the \/\/ stack contents makes sense and the dict stack is \/\/ updated. clear_tv(tv); --ectx->ec_stack.ga_len; tv = STACK_TV_BOT(-1); (void) dict_stack_save(tv); tv->v_type = VAR_NUMBER; tv->vval.v_number = 0; goto on_fatal_error; } clear_tv(tv); --ectx->ec_stack.ga_len; \/\/ Put the dict used on the dict stack, it might be used by \/\/ a dict function later. tv = STACK_TV_BOT(-1); if (dict_stack_save(tv) == FAIL) goto on_fatal_error; copy_tv(&di->di_tv, tv); } break; \/\/ dict member with string key case ISN_STRINGMEMBER: { dict_T *dict; dictitem_T *di; tv = STACK_TV_BOT(-1); if (tv->v_type != VAR_DICT || tv->vval.v_dict == NULL) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_dictionary_required)); goto on_error; } dict = tv->vval.v_dict; if ((di = dict_find(dict, iptr->isn_arg.string, -1)) == NULL) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_key_not_present_in_dictionary), iptr->isn_arg.string); goto on_error; } \/\/ Put the dict used on the dict stack, it might be used by \/\/ a dict function later. if (dict_stack_save(tv) == FAIL) goto on_fatal_error; copy_tv(&di->di_tv, tv); } break; case ISN_CLEARDICT: dict_stack_drop(); break; case ISN_USEDICT: { typval_T *dict_tv = dict_stack_get_tv(); \/\/ Turn \"dict.Func\" into a partial for \"Func\" bound to \/\/ \"dict\". Don't do this when \"Func\" is already a partial \/\/ that was bound explicitly (pt_auto is FALSE). tv = STACK_TV_BOT(-1); if (dict_tv != NULL && dict_tv->v_type == VAR_DICT && dict_tv->vval.v_dict != NULL && (tv->v_type == VAR_FUNC || (tv->v_type == VAR_PARTIAL && (tv->vval.v_partial->pt_auto || tv->vval.v_partial->pt_dict == NULL)))) dict_tv->vval.v_dict = make_partial(dict_tv->vval.v_dict, tv); dict_stack_drop(); } break; case ISN_NEGATENR: tv = STACK_TV_BOT(-1); if (tv->v_type != VAR_NUMBER #ifdef FEAT_FLOAT && tv->v_type != VAR_FLOAT #endif ) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_number_expected)); goto on_error; } #ifdef FEAT_FLOAT if (tv->v_type == VAR_FLOAT) tv->vval.v_float = -tv->vval.v_float; else #endif tv->vval.v_number = -tv->vval.v_number; break; case ISN_CHECKNR: { int error = FALSE; tv = STACK_TV_BOT(-1); SOURCING_LNUM = iptr->isn_lnum; if (check_not_string(tv) == FAIL) goto on_error; (void)tv_get_number_chk(tv, &error); if (error) goto on_error; } break; case ISN_CHECKTYPE: { checktype_T *ct = &iptr->isn_arg.type; tv = STACK_TV_BOT((int)ct->ct_off); SOURCING_LNUM = iptr->isn_lnum; if (!ectx->ec_where.wt_variable) ectx->ec_where.wt_index = ct->ct_arg_idx; if (check_typval_type(ct->ct_type, tv, ectx->ec_where) == FAIL) goto on_error; if (!ectx->ec_where.wt_variable) ectx->ec_where.wt_index = 0; \/\/ number 0 is FALSE, number 1 is TRUE if (tv->v_type == VAR_NUMBER && ct->ct_type->tt_type == VAR_BOOL && (tv->vval.v_number == 0 || tv->vval.v_number == 1)) { tv->v_type = VAR_BOOL; tv->vval.v_number = tv->vval.v_number ? VVAL_TRUE : VVAL_FALSE; } } break; case ISN_CHECKLEN: { int min_len = iptr->isn_arg.checklen.cl_min_len; list_T *list = NULL; tv = STACK_TV_BOT(-1); if (tv->v_type == VAR_LIST) list = tv->vval.v_list; if (list == NULL || list->lv_len < min_len || (list->lv_len > min_len && !iptr->isn_arg.checklen.cl_more_OK)) { SOURCING_LNUM = iptr->isn_lnum; semsg(_(e_expected_nr_items_but_got_nr), min_len, list == NULL ? 0 : list->lv_len); goto on_error; } } break; case ISN_SETTYPE: { checktype_T *ct = &iptr->isn_arg.type; tv = STACK_TV_BOT(-1); if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL) { free_type(tv->vval.v_dict->dv_type); tv->vval.v_dict->dv_type = alloc_type(ct->ct_type); } else if (tv->v_type == VAR_LIST && tv->vval.v_list != NULL) { free_type(tv->vval.v_list->lv_type); tv->vval.v_list->lv_type = alloc_type(ct->ct_type); } } break; case ISN_2BOOL: case ISN_COND2BOOL: { int n; int error = FALSE; if (iptr->isn_type == ISN_2BOOL) { tv = STACK_TV_BOT(iptr->isn_arg.tobool.offset); n = tv2bool(tv); if (iptr->isn_arg.tobool.invert) n = !n; } else { tv = STACK_TV_BOT(-1); SOURCING_LNUM = iptr->isn_lnum; n = tv_get_bool_chk(tv, &error); if (error) goto on_error; } clear_tv(tv); tv->v_type = VAR_BOOL; tv->vval.v_number = n ? VVAL_TRUE : VVAL_FALSE; } break; case ISN_2STRING: case ISN_2STRING_ANY: SOURCING_LNUM = iptr->isn_lnum; if (do_2string(STACK_TV_BOT(iptr->isn_arg.tostring.offset), iptr->isn_type == ISN_2STRING_ANY, iptr->isn_arg.tostring.tolerant) == FAIL) goto on_error; break; case ISN_RANGE: { exarg_T ea; char *errormsg; ea.line2 = 0; ea.addr_count = 0; ea.addr_type = ADDR_LINES; ea.cmd = iptr->isn_arg.string; ea.skip = FALSE; if (parse_cmd_address(&ea, &errormsg, FALSE) == FAIL) goto on_error; if (GA_GROW_FAILS(&ectx->ec_stack, 1)) goto theend; ++ectx->ec_stack.ga_len; tv = STACK_TV_BOT(-1); tv->v_type = VAR_NUMBER; tv->v_lock = 0; if (ea.addr_count == 0) tv->vval.v_number = curwin->w_cursor.lnum; else tv->vval.v_number = ea.line2; } break; case ISN_PUT: { int regname = iptr->isn_arg.put.put_regname; linenr_T lnum = iptr->isn_arg.put.put_lnum; char_u *expr = NULL; int dir = FORWARD; if (lnum < -2) { \/\/ line number was put on the stack by ISN_RANGE tv = STACK_TV_BOT(-1); curwin->w_cursor.lnum = tv->vval.v_number; if (lnum == LNUM_VARIABLE_RANGE_ABOVE) dir = BACKWARD; --ectx->ec_stack.ga_len; } else if (lnum == -2) \/\/ :put! above cursor dir = BACKWARD; else if (lnum >= 0) curwin->w_cursor.lnum = iptr->isn_arg.put.put_lnum; if (regname == '=') { tv = STACK_TV_BOT(-1); if (tv->v_type == VAR_STRING) expr = tv->vval.v_string; else { expr = typval2string(tv, TRUE); \/\/ allocates value clear_tv(tv); } --ectx->ec_stack.ga_len; } check_cursor(); do_put(regname, expr, dir, 1L, PUT_LINE|PUT_CURSLINE); vim_free(expr); } break; case ISN_CMDMOD: ectx->ec_funclocal.floc_save_cmdmod = cmdmod; ectx->ec_funclocal.floc_restore_cmdmod = TRUE; ectx->ec_funclocal.floc_restore_cmdmod_stacklen = ectx->ec_stack.ga_len; cmdmod = *iptr->isn_arg.cmdmod.cf_cmdmod; apply_cmdmod(&cmdmod); break; case ISN_CMDMOD_REV: \/\/ filter regprog is owned by the instruction, don't free it cmdmod.cmod_filter_regmatch.regprog = NULL; undo_cmdmod(&cmdmod); cmdmod = ectx->ec_funclocal.floc_save_cmdmod; ectx->ec_funclocal.floc_restore_cmdmod = FALSE; break; case ISN_UNPACK: { int count = iptr->isn_arg.unpack.unp_count; int semicolon = iptr->isn_arg.unpack.unp_semicolon; list_T *l; listitem_T *li; int i; \/\/ Check there is a valid list to unpack. tv = STACK_TV_BOT(-1); if (tv->v_type != VAR_LIST) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_for_argument_must_be_sequence_of_lists)); goto on_error; } l = tv->vval.v_list; if (l == NULL || l->lv_len < (semicolon ? count - 1 : count)) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_list_value_does_not_have_enough_items)); goto on_error; } else if (!semicolon && l->lv_len > count) { SOURCING_LNUM = iptr->isn_lnum; emsg(_(e_list_value_has_more_items_than_targets)); goto on_error; } CHECK_LIST_MATERIALIZE(l); if (GA_GROW_FAILS(&ectx->ec_stack, count - 1)) goto theend; ectx->ec_stack.ga_len += count - 1; \/\/ Variable after semicolon gets a list with the remaining \/\/ items. if (semicolon) { list_T *rem_list = list_alloc_with_items(l->lv_len - count + 1); if (rem_list == NULL) goto theend; tv = STACK_TV_BOT(-count); tv->vval.v_list = rem_list; ++rem_list->lv_refcount; tv->v_lock = 0; li = l->lv_first; for (i = 0; i < count - 1; ++i) li = li->li_next; for (i = 0; li != NULL; ++i) { list_set_item(rem_list, i, &li->li_tv); li = li->li_next; } --count; } \/\/ Produce the values in reverse order, first item last. li = l->lv_first; for (i = 0; i < count; ++i) { tv = STACK_TV_BOT(-i - 1); copy_tv(&li->li_tv, tv); li = li->li_next; } list_unref(l); } break; case ISN_PROF_START: case ISN_PROF_END: { #ifdef FEAT_PROFILE funccall_T cookie; ufunc_T *cur_ufunc = (((dfunc_T *)def_functions.ga_data) + ectx->ec_dfunc_idx)->df_ufunc; cookie.func = cur_ufunc; if (iptr->isn_type == ISN_PROF_START) { func_line_start(&cookie, iptr->isn_lnum); \/\/ if we get here the instruction is executed func_line_exec(&cookie); } else func_line_end(&cookie); #endif } break; case ISN_DEBUG: handle_debug(iptr, ectx); break; case ISN_SHUFFLE: { typval_T tmp_tv; int item = iptr->isn_arg.shuffle.shfl_item; int up = iptr->isn_arg.shuffle.shfl_up; tmp_tv = *STACK_TV_BOT(-item); for ( ; up > 0 && item > 1; --up) { *STACK_TV_BOT(-item) = *STACK_TV_BOT(-item + 1); --item; } *STACK_TV_BOT(-item) = tmp_tv; } break; case ISN_DROP: --ectx->ec_stack.ga_len; clear_tv(STACK_TV_BOT(0)); ectx->ec_where.wt_index = 0; ectx->ec_where.wt_variable = FALSE; break; } continue; func_return: \/\/ Restore previous function. If the frame pointer is where we started \/\/ then there is none and we are done. if (ectx->ec_frame_idx == ectx->ec_initial_frame_idx) goto done; if (func_return(ectx) == FAIL) \/\/ only fails when out of memory goto theend; continue; on_error: \/\/ Jump here for an error that does not require aborting execution. \/\/ If \"emsg_silent\" is set then ignore the error, unless it was set \/\/ when calling the function. if (did_emsg_cumul + did_emsg == ectx->ec_did_emsg_before && emsg_silent && did_emsg_def == 0) { \/\/ If a sequence of instructions causes an error while \":silent!\" \/\/ was used, restore the stack length and jump ahead to restoring \/\/ the cmdmod. if (ectx->ec_funclocal.floc_restore_cmdmod) { while (ectx->ec_stack.ga_len > ectx->ec_funclocal.floc_restore_cmdmod_stacklen) { --ectx->ec_stack.ga_len; clear_tv(STACK_TV_BOT(0)); } while (ectx->ec_instr[ectx->ec_iidx].isn_type != ISN_CMDMOD_REV) ++ectx->ec_iidx; } continue; } on_fatal_error: \/\/ Jump here for an error that messes up the stack. \/\/ If we are not inside a try-catch started here, abort execution. if (trylevel <= ectx->ec_trylevel_at_start) goto theend; } done: ret = OK; theend: dict_stack_clear(dict_stack_len_at_start); ectx->ec_trylevel_at_start = save_trylevel_at_start; return ret; }","output":{"is_vulnerable":"True","vulnerability_types":["Use After Free"],"explanation":"vim is vulnerable to Use After Free","severity_level":"NoInfo","cwe":"CWE-416","cve":"CVE-2022-0156"}} -{"idx":160986,"input":"mrb_vm_exec(mrb_state *mrb, struct RProc *proc, mrb_code *pc) { \/* mrb_assert(mrb_proc_cfunc_p(proc)) *\/ mrb_irep *irep = proc->body.irep; mrb_value *pool = irep->pool; mrb_sym *syms = irep->syms; mrb_code i; int ai = mrb_gc_arena_save(mrb); struct mrb_jmpbuf *prev_jmp = mrb->jmp; struct mrb_jmpbuf c_jmp; #ifdef DIRECT_THREADED static void *optable[] = { &&L_OP_NOP, &&L_OP_MOVE, &&L_OP_LOADL, &&L_OP_LOADI, &&L_OP_LOADSYM, &&L_OP_LOADNIL, &&L_OP_LOADSELF, &&L_OP_LOADT, &&L_OP_LOADF, &&L_OP_GETGLOBAL, &&L_OP_SETGLOBAL, &&L_OP_GETSPECIAL, &&L_OP_SETSPECIAL, &&L_OP_GETIV, &&L_OP_SETIV, &&L_OP_GETCV, &&L_OP_SETCV, &&L_OP_GETCONST, &&L_OP_SETCONST, &&L_OP_GETMCNST, &&L_OP_SETMCNST, &&L_OP_GETUPVAR, &&L_OP_SETUPVAR, &&L_OP_JMP, &&L_OP_JMPIF, &&L_OP_JMPNOT, &&L_OP_ONERR, &&L_OP_RESCUE, &&L_OP_POPERR, &&L_OP_RAISE, &&L_OP_EPUSH, &&L_OP_EPOP, &&L_OP_SEND, &&L_OP_SENDB, &&L_OP_FSEND, &&L_OP_CALL, &&L_OP_SUPER, &&L_OP_ARGARY, &&L_OP_ENTER, &&L_OP_KARG, &&L_OP_KDICT, &&L_OP_RETURN, &&L_OP_TAILCALL, &&L_OP_BLKPUSH, &&L_OP_ADD, &&L_OP_ADDI, &&L_OP_SUB, &&L_OP_SUBI, &&L_OP_MUL, &&L_OP_DIV, &&L_OP_EQ, &&L_OP_LT, &&L_OP_LE, &&L_OP_GT, &&L_OP_GE, &&L_OP_ARRAY, &&L_OP_ARYCAT, &&L_OP_ARYPUSH, &&L_OP_AREF, &&L_OP_ASET, &&L_OP_APOST, &&L_OP_STRING, &&L_OP_STRCAT, &&L_OP_HASH, &&L_OP_LAMBDA, &&L_OP_RANGE, &&L_OP_OCLASS, &&L_OP_CLASS, &&L_OP_MODULE, &&L_OP_EXEC, &&L_OP_METHOD, &&L_OP_SCLASS, &&L_OP_TCLASS, &&L_OP_DEBUG, &&L_OP_STOP, &&L_OP_ERR, }; #endif mrb_bool exc_catched = FALSE; RETRY_TRY_BLOCK: MRB_TRY(&c_jmp) { if (exc_catched) { exc_catched = FALSE; if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK) goto L_BREAK; goto L_RAISE; } mrb->jmp = &c_jmp; mrb->c->ci->proc = proc; mrb->c->ci->nregs = irep->nregs; #define regs (mrb->c->stack) INIT_DISPATCH { CASE(OP_NOP) { \/* do nothing *\/ NEXT; } CASE(OP_MOVE) { \/* A B R(A) := R(B) *\/ int a = GETARG_A(i); int b = GETARG_B(i); regs[a] = regs[b]; NEXT; } CASE(OP_LOADL) { \/* A Bx R(A) := Pool(Bx) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); #ifdef MRB_WORD_BOXING mrb_value val = pool[bx]; #ifndef MRB_WITHOUT_FLOAT if (mrb_float_p(val)) { val = mrb_float_value(mrb, mrb_float(val)); } #endif regs[a] = val; #else regs[a] = pool[bx]; #endif NEXT; } CASE(OP_LOADI) { \/* A sBx R(A) := sBx *\/ int a = GETARG_A(i); mrb_int bx = GETARG_sBx(i); SET_INT_VALUE(regs[a], bx); NEXT; } CASE(OP_LOADSYM) { \/* A Bx R(A) := Syms(Bx) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); SET_SYM_VALUE(regs[a], syms[bx]); NEXT; } CASE(OP_LOADSELF) { \/* A R(A) := self *\/ int a = GETARG_A(i); regs[a] = regs[0]; NEXT; } CASE(OP_LOADT) { \/* A R(A) := true *\/ int a = GETARG_A(i); SET_TRUE_VALUE(regs[a]); NEXT; } CASE(OP_LOADF) { \/* A R(A) := false *\/ int a = GETARG_A(i); SET_FALSE_VALUE(regs[a]); NEXT; } CASE(OP_GETGLOBAL) { \/* A Bx R(A) := getglobal(Syms(Bx)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_gv_get(mrb, syms[bx]); regs[a] = val; NEXT; } CASE(OP_SETGLOBAL) { \/* A Bx setglobal(Syms(Bx), R(A)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_gv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETSPECIAL) { \/* A Bx R(A) := Special[Bx] *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_vm_special_get(mrb, bx); regs[a] = val; NEXT; } CASE(OP_SETSPECIAL) { \/* A Bx Special[Bx] := R(A) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_special_set(mrb, bx, regs[a]); NEXT; } CASE(OP_GETIV) { \/* A Bx R(A) := ivget(Bx) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_vm_iv_get(mrb, syms[bx]); regs[a] = val; NEXT; } CASE(OP_SETIV) { \/* A Bx ivset(Syms(Bx),R(A)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_iv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETCV) { \/* A Bx R(A) := cvget(Syms(Bx)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val; ERR_PC_SET(mrb, pc); val = mrb_vm_cv_get(mrb, syms[bx]); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETCV) { \/* A Bx cvset(Syms(Bx),R(A)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_cv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETCONST) { \/* A Bx R(A) := constget(Syms(Bx)) *\/ mrb_value val; int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_sym sym = syms[bx]; ERR_PC_SET(mrb, pc); val = mrb_vm_const_get(mrb, sym); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETCONST) { \/* A Bx constset(Syms(Bx),R(A)) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_const_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETMCNST) { \/* A Bx R(A) := R(A)::Syms(Bx) *\/ mrb_value val; int a = GETARG_A(i); int bx = GETARG_Bx(i); ERR_PC_SET(mrb, pc); val = mrb_const_get(mrb, regs[a], syms[bx]); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETMCNST) { \/* A Bx R(A+1)::Syms(Bx) := R(A) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_const_set(mrb, regs[a+1], syms[bx], regs[a]); NEXT; } CASE(OP_GETUPVAR) { \/* A B C R(A) := uvget(B,C) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value *regs_a = regs + a; struct REnv *e = uvenv(mrb, c); if (e && b < MRB_ENV_STACK_LEN(e)) { *regs_a = e->stack[b]; } else { *regs_a = mrb_nil_value(); } NEXT; } CASE(OP_SETUPVAR) { \/* A B C uvset(B,C,R(A)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); struct REnv *e = uvenv(mrb, c); if (e) { mrb_value *regs_a = regs + a; if (b < MRB_ENV_STACK_LEN(e)) { e->stack[b] = *regs_a; mrb_write_barrier(mrb, (struct RBasic*)e); } } NEXT; } CASE(OP_JMP) { \/* sBx pc+=sBx *\/ int sbx = GETARG_sBx(i); pc += sbx; JUMP; } CASE(OP_JMPIF) { \/* A sBx if R(A) pc+=sBx *\/ int a = GETARG_A(i); int sbx = GETARG_sBx(i); if (mrb_test(regs[a])) { pc += sbx; JUMP; } NEXT; } CASE(OP_JMPNOT) { \/* A sBx if !R(A) pc+=sBx *\/ int a = GETARG_A(i); int sbx = GETARG_sBx(i); if (!mrb_test(regs[a])) { pc += sbx; JUMP; } NEXT; } CASE(OP_ONERR) { \/* sBx pc+=sBx on exception *\/ int sbx = GETARG_sBx(i); if (mrb->c->rsize <= mrb->c->ci->ridx) { if (mrb->c->rsize == 0) mrb->c->rsize = RESCUE_STACK_INIT_SIZE; else mrb->c->rsize *= 2; mrb->c->rescue = (mrb_code **)mrb_realloc(mrb, mrb->c->rescue, sizeof(mrb_code*) * mrb->c->rsize); } mrb->c->rescue[mrb->c->ci->ridx++] = pc + sbx; NEXT; } CASE(OP_RESCUE) { \/* A B R(A) := exc; clear(exc); R(B) := matched (bool) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value exc; if (c == 0) { exc = mrb_obj_value(mrb->exc); mrb->exc = 0; } else { \/* continued; exc taken from R(A) *\/ exc = regs[a]; } if (b != 0) { mrb_value e = regs[b]; struct RClass *ec; switch (mrb_type(e)) { case MRB_TT_CLASS: case MRB_TT_MODULE: break; default: { mrb_value exc; exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, \"class or module required for rescue clause\"); mrb_exc_set(mrb, exc); goto L_RAISE; } } ec = mrb_class_ptr(e); regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec)); } if (a != 0 && c == 0) { regs[a] = exc; } NEXT; } CASE(OP_POPERR) { \/* A A.times{rescue_pop()} *\/ int a = GETARG_A(i); mrb->c->ci->ridx -= a; NEXT; } CASE(OP_RAISE) { \/* A raise(R(A)) *\/ int a = GETARG_A(i); mrb_exc_set(mrb, regs[a]); goto L_RAISE; } CASE(OP_EPUSH) { \/* Bx ensure_push(SEQ[Bx]) *\/ int bx = GETARG_Bx(i); struct RProc *p; p = mrb_closure_new(mrb, irep->reps[bx]); \/* push ensure_stack *\/ if (mrb->c->esize <= mrb->c->eidx+1) { if (mrb->c->esize == 0) mrb->c->esize = ENSURE_STACK_INIT_SIZE; else mrb->c->esize *= 2; mrb->c->ensure = (struct RProc **)mrb_realloc(mrb, mrb->c->ensure, sizeof(struct RProc*) * mrb->c->esize); } mrb->c->ensure[mrb->c->eidx++] = p; mrb->c->ensure[mrb->c->eidx] = NULL; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EPOP) { \/* A A.times{ensure_pop().call} *\/ int a = GETARG_A(i); mrb_callinfo *ci = mrb->c->ci; int n, epos = ci->epos; mrb_value self = regs[0]; struct RClass *target_class = ci->target_class; if (mrb->c->eidx <= epos) { NEXT; } if (a > mrb->c->eidx - epos) a = mrb->c->eidx - epos; pc = pc + 1; for (n=0; nc->ensure[epos+n]; mrb->c->ensure[epos+n] = NULL; if (proc == NULL) continue; irep = proc->body.irep; ci = cipush(mrb); ci->mid = ci[-1].mid; ci->argc = 0; ci->proc = proc; ci->stackent = mrb->c->stack; ci->nregs = irep->nregs; ci->target_class = target_class; ci->pc = pc; ci->acc = ci[-1].nregs; mrb->c->stack += ci->acc; stack_extend(mrb, ci->nregs); regs[0] = self; pc = irep->iseq; } pool = irep->pool; syms = irep->syms; mrb->c->eidx = epos; JUMP; } CASE(OP_LOADNIL) { \/* A R(A) := nil *\/ int a = GETARG_A(i); SET_NIL_VALUE(regs[a]); NEXT; } CASE(OP_SENDB) { \/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C),&R(A+C+1))*\/ \/* fall through *\/ }; L_SEND: CASE(OP_SEND) { \/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C)) *\/ int a = GETARG_A(i); int n = GETARG_C(i); int argc = (n == CALL_MAXARGS) ? -1 : n; int bidx = (argc < 0) ? a+2 : a+n+1; mrb_method_t m; struct RClass *c; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; mrb_sym mid = syms[GETARG_B(i)]; mrb_assert(bidx < ci->nregs); recv = regs[a]; if (GET_OPCODE(i) != OP_SENDB) { SET_NIL_VALUE(regs[bidx]); blk = regs[bidx]; } else { blk = regs[bidx]; if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) { blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, \"Proc\", \"to_proc\"); \/* The stack might have been reallocated during mrb_convert_type(), see #3622 *\/ regs[bidx] = blk; } } c = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_sym missing = mrb_intern_lit(mrb, \"method_missing\"); m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m) || (missing == mrb->c->ci->mid && mrb_obj_eq(mrb, regs[0], recv))) { mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1); ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } if (argc >= 0) { if (a+2 >= irep->nregs) { stack_extend(mrb, a+3); } regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1); regs[a+2] = blk; argc = -1; } mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(mid)); mid = missing; } \/* push callinfo *\/ ci = cipush(mrb); ci->mid = mid; ci->stackent = mrb->c->stack; ci->target_class = c; ci->argc = argc; ci->pc = pc + 1; ci->acc = a; \/* prepare stack *\/ mrb->c->stack += a; if (MRB_METHOD_CFUNC_P(m)) { ci->nregs = (argc < 0) ? 3 : n+2; if (MRB_METHOD_PROC_P(m)) { struct RProc *p = MRB_METHOD_PROC(m); ci->proc = p; recv = p->body.func(mrb, recv); } else { recv = MRB_METHOD_FUNC(m)(mrb, recv); } mrb_gc_arena_restore(mrb, ai); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (GET_OPCODE(i) == OP_SENDB) { if (mrb_type(blk) == MRB_TT_PROC) { struct RProc *p = mrb_proc_ptr(blk); if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == ci[-1].env) { p->flags |= MRB_PROC_ORPHAN; } } } if (!ci->target_class) { \/* return from context modifying method (resume\/yield) *\/ if (ci->acc == CI_ACC_RESUMED) { mrb->jmp = prev_jmp; return recv; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->stack[0] = recv; \/* pop stackpos *\/ mrb->c->stack = ci->stackent; pc = ci->pc; cipop(mrb); JUMP; } else { \/* setup environment for calling method *\/ proc = ci->proc = MRB_METHOD_PROC(m); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs); pc = irep->iseq; JUMP; } } CASE(OP_FSEND) { \/* A B C R(A) := fcall(R(A),Syms(B),R(A+1),... ,R(A+C-1)) *\/ \/* not implemented yet *\/ NEXT; } CASE(OP_CALL) { \/* A R(A) := self.call(frame.argc, frame.argv) *\/ mrb_callinfo *ci; mrb_value recv = mrb->c->stack[0]; struct RProc *m = mrb_proc_ptr(recv); \/* replace callinfo *\/ ci = mrb->c->ci; ci->target_class = MRB_PROC_TARGET_CLASS(m); ci->proc = m; if (MRB_PROC_ENV_P(m)) { mrb_sym mid; struct REnv *e = MRB_PROC_ENV(m); mid = e->mid; if (mid) ci->mid = mid; if (!e->stack) { e->stack = mrb->c->stack; } } \/* prepare stack *\/ if (MRB_PROC_CFUNC_P(m)) { recv = MRB_PROC_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; \/* pop stackpos *\/ ci = mrb->c->ci; mrb->c->stack = ci->stackent; regs[ci->acc] = recv; pc = ci->pc; cipop(mrb); irep = mrb->c->ci->proc->body.irep; pool = irep->pool; syms = irep->syms; JUMP; } else { \/* setup environment for calling method *\/ proc = m; irep = m->body.irep; if (!irep) { mrb->c->stack[0] = mrb_nil_value(); goto L_RETURN; } pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, ci->nregs); if (ci->argc < 0) { if (irep->nregs > 3) { stack_clear(regs+3, irep->nregs-3); } } else if (ci->argc+2 < irep->nregs) { stack_clear(regs+ci->argc+2, irep->nregs-ci->argc-2); } if (MRB_PROC_ENV_P(m)) { regs[0] = MRB_PROC_ENV(m)->stack[0]; } pc = irep->iseq; JUMP; } } CASE(OP_SUPER) { \/* A C R(A) := super(R(A+1),... ,R(A+C+1)) *\/ int a = GETARG_A(i); int n = GETARG_C(i); int argc = (n == CALL_MAXARGS) ? -1 : n; int bidx = (argc < 0) ? a+2 : a+n+1; mrb_method_t m; struct RClass *c; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; mrb_sym mid = ci->mid; struct RClass* target_class = MRB_PROC_TARGET_CLASS(ci->proc); mrb_assert(bidx < ci->nregs); if (mid == 0 || !target_class) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (target_class->tt == MRB_TT_MODULE) { target_class = ci->target_class; if (target_class->tt != MRB_TT_ICLASS) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, \"superclass info lost [mruby limitations]\"); mrb_exc_set(mrb, exc); goto L_RAISE; } } recv = regs[0]; if (!mrb_obj_is_kind_of(mrb, recv, target_class)) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, \"self has wrong type to call super in this context\"); mrb_exc_set(mrb, exc); goto L_RAISE; } blk = regs[bidx]; if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) { blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, \"Proc\", \"to_proc\"); \/* The stack or ci stack might have been reallocated during mrb_convert_type(), see #3622 and #3784 *\/ regs[bidx] = blk; ci = mrb->c->ci; } c = target_class->super; m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_sym missing = mrb_intern_lit(mrb, \"method_missing\"); if (mid != missing) { c = mrb_class(mrb, recv); } m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m)) { mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1); ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } mid = missing; if (argc >= 0) { if (a+2 >= ci->nregs) { stack_extend(mrb, a+3); } regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1); regs[a+2] = blk; argc = -1; } mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(ci->mid)); } \/* push callinfo *\/ ci = cipush(mrb); ci->mid = mid; ci->stackent = mrb->c->stack; ci->target_class = c; ci->pc = pc + 1; ci->argc = argc; \/* prepare stack *\/ mrb->c->stack += a; mrb->c->stack[0] = recv; if (MRB_METHOD_CFUNC_P(m)) { mrb_value v; ci->nregs = (argc < 0) ? 3 : n+2; if (MRB_METHOD_PROC_P(m)) { ci->proc = MRB_METHOD_PROC(m); } v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (!ci->target_class) { \/* return from context modifying method (resume\/yield) *\/ if (ci->acc == CI_ACC_RESUMED) { mrb->jmp = prev_jmp; return v; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->stack[0] = v; \/* pop stackpos *\/ mrb->c->stack = ci->stackent; pc = ci->pc; cipop(mrb); JUMP; } else { \/* fill callinfo *\/ ci->acc = a; \/* setup environment for calling method *\/ proc = ci->proc = MRB_METHOD_PROC(m); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs); pc = irep->iseq; JUMP; } } CASE(OP_ARGARY) { \/* A Bx R(A) := argument array (16=6:1:5:4) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); int m1 = (bx>>10)&0x3f; int r = (bx>>9)&0x1; int m2 = (bx>>4)&0x1f; int lv = (bx>>0)&0xf; mrb_value *stack; if (mrb->c->ci->mid == 0 || mrb->c->ci->target_class == NULL) { mrb_value exc; L_NOSUPER: exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, \"super called outside of method\"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e) goto L_NOSUPER; if (MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) goto L_NOSUPER; stack = e->stack + 1; } if (r == 0) { regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack); } else { mrb_value *pp = NULL; struct RArray *rest; int len = 0; if (mrb_array_p(stack[m1])) { struct RArray *ary = mrb_ary_ptr(stack[m1]); pp = ARY_PTR(ary); len = (int)ARY_LEN(ary); } regs[a] = mrb_ary_new_capa(mrb, m1+len+m2); rest = mrb_ary_ptr(regs[a]); if (m1 > 0) { stack_copy(ARY_PTR(rest), stack, m1); } if (len > 0) { stack_copy(ARY_PTR(rest)+m1, pp, len); } if (m2 > 0) { stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2); } ARY_SET_LEN(rest, m1+len+m2); } regs[a+1] = stack[m1+r+m2]; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ENTER) { \/* Ax arg setup according to flags (23=5:5:1:5:5:1:1) *\/ \/* number of optional arguments times OP_JMP should follow *\/ mrb_aspec ax = GETARG_Ax(i); int m1 = MRB_ASPEC_REQ(ax); int o = MRB_ASPEC_OPT(ax); int r = MRB_ASPEC_REST(ax); int m2 = MRB_ASPEC_POST(ax); \/* unused int k = MRB_ASPEC_KEY(ax); int kd = MRB_ASPEC_KDICT(ax); int b = MRB_ASPEC_BLOCK(ax); *\/ int argc = mrb->c->ci->argc; mrb_value *argv = regs+1; mrb_value *argv0 = argv; int len = m1 + o + r + m2; mrb_value *blk = &argv[argc < 0 ? 1 : argc]; if (argc < 0) { struct RArray *ary = mrb_ary_ptr(regs[1]); argv = ARY_PTR(ary); argc = (int)ARY_LEN(ary); mrb_gc_protect(mrb, regs[1]); } if (mrb->c->ci->proc && MRB_PROC_STRICT_P(mrb->c->ci->proc)) { if (argc >= 0) { if (argc < m1 + m2 || (r == 0 && argc > len)) { argnum_error(mrb, m1+m2); goto L_RAISE; } } } else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) { mrb_gc_protect(mrb, argv[0]); argc = (int)RARRAY_LEN(argv[0]); argv = RARRAY_PTR(argv[0]); } if (argc < len) { int mlen = m2; if (argc < m1+m2) { if (m1 < argc) mlen = argc - m1; else mlen = 0; } regs[len+1] = *blk; \/* move block *\/ SET_NIL_VALUE(regs[argc+1]); if (argv0 != argv) { value_move(®s[1], argv, argc-mlen); \/* m1 + o *\/ } if (argc < m1) { stack_clear(®s[argc+1], m1-argc); } if (mlen) { value_move(®s[len-m2+1], &argv[argc-mlen], mlen); } if (mlen < m2) { stack_clear(®s[len-m2+mlen+1], m2-mlen); } if (r) { regs[m1+o+1] = mrb_ary_new_capa(mrb, 0); } if (o == 0 || argc < m1+m2) pc++; else pc += argc - m1 - m2 + 1; } else { int rnum = 0; if (argv0 != argv) { regs[len+1] = *blk; \/* move block *\/ value_move(®s[1], argv, m1+o); } if (r) { rnum = argc-m1-o-m2; regs[m1+o+1] = mrb_ary_new_from_values(mrb, rnum, argv+m1+o); } if (m2) { if (argc-m2 > m1) { value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2); } } if (argv0 == argv) { regs[len+1] = *blk; \/* move block *\/ } pc += o + 1; } mrb->c->ci->argc = len; \/* clear local (but non-argument) variables *\/ if (irep->nlocals-len-2 > 0) { stack_clear(®s[len+2], irep->nlocals-len-2); } JUMP; } CASE(OP_KARG) { \/* A B C R(A) := kdict[Syms(B)]; if C kdict.rm(Syms(B)) *\/ \/* if C == 2; raise unless kdict.empty? *\/ \/* OP_JMP should follow to skip init code *\/ NEXT; } CASE(OP_KDICT) { \/* A C R(A) := kdict *\/ NEXT; } L_RETURN: i = MKOP_AB(OP_RETURN, GETARG_A(i), OP_R_NORMAL); \/* fall through *\/ CASE(OP_RETURN) { \/* A B return R(A) (B=normal,in-block return\/break) *\/ mrb_callinfo *ci; #define ecall_adjust() do {\\ ptrdiff_t cioff = ci - mrb->c->cibase;\\ ecall(mrb);\\ ci = mrb->c->cibase + cioff;\\ } while (0) ci = mrb->c->ci; if (ci->mid) { mrb_value blk; if (ci->argc < 0) { blk = regs[2]; } else { blk = regs[ci->argc+1]; } if (mrb_type(blk) == MRB_TT_PROC) { struct RProc *p = mrb_proc_ptr(blk); if (!MRB_PROC_STRICT_P(p) && ci > mrb->c->cibase && MRB_PROC_ENV(p) == ci[-1].env) { p->flags |= MRB_PROC_ORPHAN; } } } if (mrb->exc) { mrb_callinfo *ci0; L_RAISE: ci0 = ci = mrb->c->ci; if (ci == mrb->c->cibase) { if (ci->ridx == 0) goto L_FTOP; goto L_RESCUE; } while (ci[0].ridx == ci[-1].ridx) { cipop(mrb); mrb->c->stack = ci->stackent; if (ci->acc == CI_ACC_SKIP && prev_jmp) { mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } ci = mrb->c->ci; if (ci == mrb->c->cibase) { if (ci->ridx == 0) { L_FTOP: \/* fiber top *\/ if (mrb->c == mrb->root_c) { mrb->c->stack = mrb->c->stbase; goto L_STOP; } else { struct mrb_context *c = mrb->c; while (c->eidx > ci->epos) { ecall_adjust(); } if (c->fib) { mrb_write_barrier(mrb, (struct RBasic*)c->fib); } mrb->c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; goto L_RAISE; } } break; } \/* call ensure only when we skip this callinfo *\/ if (ci[0].ridx == ci[-1].ridx) { while (mrb->c->eidx > ci->epos) { ecall_adjust(); } } } L_RESCUE: if (ci->ridx == 0) goto L_STOP; proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; if (ci < ci0) { mrb->c->stack = ci[1].stackent; } stack_extend(mrb, irep->nregs); pc = mrb->c->rescue[--ci->ridx]; } else { int acc; mrb_value v; struct RProc *dst; ci = mrb->c->ci; v = regs[GETARG_A(i)]; mrb_gc_protect(mrb, v); switch (GETARG_B(i)) { case OP_R_RETURN: \/* Fall through to OP_R_NORMAL otherwise *\/ if (ci->acc >=0 && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) { mrb_callinfo *cibase = mrb->c->cibase; dst = top_proc(mrb, proc); if (MRB_PROC_ENV_P(dst)) { struct REnv *e = MRB_PROC_ENV(dst); if (!MRB_ENV_STACK_SHARED_P(e) || e->cxt != mrb->c) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } } while (cibase <= ci && ci->proc != dst) { if (ci->acc < 0) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci--; } if (ci <= cibase) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } break; } case OP_R_NORMAL: NORMAL_RETURN: if (ci == mrb->c->cibase) { struct mrb_context *c; if (!mrb->c->prev) { \/* toplevel return *\/ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } if (mrb->c->prev->ci == mrb->c->prev->cibase) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_FIBER_ERROR, \"double resume\"); mrb_exc_set(mrb, exc); goto L_RAISE; } while (mrb->c->eidx > 0) { ecall(mrb); } \/* automatic yield at the end *\/ c = mrb->c; c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; mrb->c->status = MRB_FIBER_RUNNING; ci = mrb->c->ci; } break; case OP_R_BREAK: if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN; if (MRB_PROC_ORPHAN_P(proc)) { mrb_value exc; L_BREAK_ERROR: exc = mrb_exc_new_str_lit(mrb, E_LOCALJUMP_ERROR, \"break from proc-closure\"); mrb_exc_set(mrb, exc); goto L_RAISE; } if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_STACK_SHARED_P(MRB_PROC_ENV(proc))) { goto L_BREAK_ERROR; } else { struct REnv *e = MRB_PROC_ENV(proc); if (e == mrb->c->cibase->env && proc != mrb->c->cibase->proc) { goto L_BREAK_ERROR; } if (e->cxt != mrb->c) { goto L_BREAK_ERROR; } } while (mrb->c->eidx > mrb->c->ci->epos) { ecall_adjust(); } \/* break from fiber block *\/ if (ci == mrb->c->cibase && ci->pc) { struct mrb_context *c = mrb->c; mrb->c = c->prev; c->prev = NULL; ci = mrb->c->ci; } if (ci->acc < 0) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->exc = (struct RObject*)break_new(mrb, proc, v); mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } if (FALSE) { L_BREAK: v = ((struct RBreak*)mrb->exc)->val; proc = ((struct RBreak*)mrb->exc)->proc; mrb->exc = NULL; ci = mrb->c->ci; } mrb->c->stack = ci->stackent; proc = proc->upper; while (mrb->c->cibase < ci && ci[-1].proc != proc) { if (ci[-1].acc == CI_ACC_SKIP) { while (ci < mrb->c->ci) { cipop(mrb); } goto L_BREAK_ERROR; } ci--; } if (ci == mrb->c->cibase) { goto L_BREAK_ERROR; } break; default: \/* cannot happen *\/ break; } while (ci < mrb->c->ci) { cipop(mrb); } ci[0].ridx = ci[-1].ridx; while (mrb->c->eidx > ci->epos) { ecall_adjust(); } if (mrb->c->vmexec && !ci->target_class) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } acc = ci->acc; mrb->c->stack = ci->stackent; cipop(mrb); if (acc == CI_ACC_SKIP || acc == CI_ACC_DIRECT) { mrb_gc_arena_restore(mrb, ai); mrb->jmp = prev_jmp; return v; } pc = ci->pc; ci = mrb->c->ci; DEBUG(fprintf(stderr, \"from :%s\\n\", mrb_sym2name(mrb, ci->mid))); proc = mrb->c->ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; regs[acc] = v; mrb_gc_arena_restore(mrb, ai); } JUMP; } CASE(OP_TAILCALL) { \/* A B C return call(R(A),Syms(B),R(A+1),... ,R(A+C+1)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int n = GETARG_C(i); mrb_method_t m; struct RClass *c; mrb_callinfo *ci; mrb_value recv; mrb_sym mid = syms[b]; recv = regs[a]; c = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_value sym = mrb_symbol_value(mid); mrb_sym missing = mrb_intern_lit(mrb, \"method_missing\"); m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m)) { mrb_value args; if (n == CALL_MAXARGS) { args = regs[a+1]; } else { args = mrb_ary_new_from_values(mrb, n, regs+a+1); } ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } mid = missing; if (n == CALL_MAXARGS) { mrb_ary_unshift(mrb, regs[a+1], sym); } else { value_move(regs+a+2, regs+a+1, ++n); regs[a+1] = sym; } } \/* replace callinfo *\/ ci = mrb->c->ci; ci->mid = mid; ci->target_class = c; if (n == CALL_MAXARGS) { ci->argc = -1; } else { ci->argc = n; } \/* move stack *\/ value_move(mrb->c->stack, ®s[a], ci->argc+1); if (MRB_METHOD_CFUNC_P(m)) { mrb_value v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb->c->stack[0] = v; mrb_gc_arena_restore(mrb, ai); goto L_RETURN; } else { \/* setup environment for calling method *\/ struct RProc *p = MRB_METHOD_PROC(m); irep = p->body.irep; pool = irep->pool; syms = irep->syms; if (ci->argc < 0) { stack_extend(mrb, (irep->nregs < 3) ? 3 : irep->nregs); } else { stack_extend(mrb, irep->nregs); } pc = irep->iseq; } JUMP; } CASE(OP_BLKPUSH) { \/* A Bx R(A) := block (16=6:1:5:4) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); int m1 = (bx>>10)&0x3f; int r = (bx>>9)&0x1; int m2 = (bx>>4)&0x1f; int lv = (bx>>0)&0xf; mrb_value *stack; if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e || (!MRB_ENV_STACK_SHARED_P(e) && e->mid == 0) || MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } stack = e->stack + 1; } if (mrb_nil_p(stack[m1+r+m2])) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } regs[a] = stack[m1+r+m2]; NEXT; } #define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff)) #define OP_MATH_BODY(op,v1,v2) do {\\ v1(regs[a]) = v1(regs[a]) op v2(regs[a+1]);\\ } while(0) CASE(OP_ADD) { \/* A B C R(A) := R(A)+R(A+1) (Syms[B]=:+,C=1)*\/ int a = GETARG_A(i); \/* need to check if op is overridden *\/ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; mrb_value *regs_a = regs + a; x = mrb_fixnum(regs_a[0]); y = mrb_fixnum(regs_a[1]); if (mrb_int_add_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x + (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x + y); } #else OP_MATH_BODY(+,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x + y); } #else OP_MATH_BODY(+,mrb_float,mrb_float); #endif break; #endif case TYPES2(MRB_TT_STRING,MRB_TT_STRING): regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); break; default: goto L_SEND; } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_SUB) { \/* A B C R(A) := R(A)-R(A+1) (Syms[B]=:-,C=1)*\/ int a = GETARG_A(i); \/* need to check if op is overridden *\/ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; x = mrb_fixnum(regs[a]); y = mrb_fixnum(regs[a+1]); if (mrb_int_sub_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x - y); } #else OP_MATH_BODY(-,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x - y); } #else OP_MATH_BODY(-,mrb_float,mrb_float); #endif break; #endif default: goto L_SEND; } NEXT; } CASE(OP_MUL) { \/* A B C R(A) := R(A)*R(A+1) (Syms[B]=:*,C=1)*\/ int a = GETARG_A(i); \/* need to check if op is overridden *\/ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; x = mrb_fixnum(regs[a]); y = mrb_fixnum(regs[a+1]); if (mrb_int_mul_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x * y); } #else OP_MATH_BODY(*,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x * y); } #else OP_MATH_BODY(*,mrb_float,mrb_float); #endif break; #endif default: goto L_SEND; } NEXT; } CASE(OP_DIV) { \/* A B C R(A) := R(A)\/R(A+1) (Syms[B]=:\/,C=1)*\/ int a = GETARG_A(i); #ifndef MRB_WITHOUT_FLOAT double x, y, f; #endif \/* need to check if op is overridden *\/ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): #ifdef MRB_WITHOUT_FLOAT { mrb_int x = mrb_fixnum(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_INT_VALUE(regs[a], y ? x \/ y : 0); } break; #else x = (mrb_float)mrb_fixnum(regs[a]); y = (mrb_float)mrb_fixnum(regs[a+1]); break; case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): x = (mrb_float)mrb_fixnum(regs[a]); y = mrb_float(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): x = mrb_float(regs[a]); y = (mrb_float)mrb_fixnum(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): x = mrb_float(regs[a]); y = mrb_float(regs[a+1]); break; #endif default: goto L_SEND; } #ifndef MRB_WITHOUT_FLOAT if (y == 0) { if (x > 0) f = INFINITY; else if (x < 0) f = -INFINITY; else \/* if (x == 0) *\/ f = NAN; } else { f = x \/ y; } SET_FLOAT_VALUE(mrb, regs[a], f); #endif NEXT; } CASE(OP_ADDI) { \/* A B C R(A) := R(A)+C (Syms[B]=:+)*\/ int a = GETARG_A(i); \/* need to check if + is overridden *\/ switch (mrb_type(regs[a])) { case MRB_TT_FIXNUM: { mrb_int x = mrb_fixnum(regs[a]); mrb_int y = GETARG_C(i); mrb_int z; if (mrb_int_add_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case MRB_TT_FLOAT: #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); SET_FLOAT_VALUE(mrb, regs[a], x + GETARG_C(i)); } #else mrb_float(regs[a]) += GETARG_C(i); #endif break; #endif default: SET_INT_VALUE(regs[a+1], GETARG_C(i)); i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1); goto L_SEND; } NEXT; } CASE(OP_SUBI) { \/* A B C R(A) := R(A)-C (Syms[B]=:-)*\/ int a = GETARG_A(i); mrb_value *regs_a = regs + a; \/* need to check if + is overridden *\/ switch (mrb_type(regs_a[0])) { case MRB_TT_FIXNUM: { mrb_int x = mrb_fixnum(regs_a[0]); mrb_int y = GETARG_C(i); mrb_int z; if (mrb_int_sub_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x - (mrb_float)y); break; #endif } SET_INT_VALUE(regs_a[0], z); } break; #ifndef MRB_WITHOUT_FLOAT case MRB_TT_FLOAT: #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); SET_FLOAT_VALUE(mrb, regs[a], x - GETARG_C(i)); } #else mrb_float(regs_a[0]) -= GETARG_C(i); #endif break; #endif default: SET_INT_VALUE(regs_a[1], GETARG_C(i)); i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1); goto L_SEND; } NEXT; } #define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1])) #ifdef MRB_WITHOUT_FLOAT #define OP_CMP(op) do {\\ int result;\\ \/* need to check if - is overridden *\/\\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\ break;\\ default:\\ goto L_SEND;\\ }\\ if (result) {\\ SET_TRUE_VALUE(regs[a]);\\ }\\ else {\\ SET_FALSE_VALUE(regs[a]);\\ }\\ } while(0) #else #define OP_CMP(op) do {\\ int result;\\ \/* need to check if - is overridden *\/\\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\\ break;\\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\\ break;\\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\\ result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\\ break;\\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\\ result = OP_CMP_BODY(op,mrb_float,mrb_float);\\ break;\\ default:\\ goto L_SEND;\\ }\\ if (result) {\\ SET_TRUE_VALUE(regs[a]);\\ }\\ else {\\ SET_FALSE_VALUE(regs[a]);\\ }\\ } while(0) #endif CASE(OP_EQ) { \/* A B C R(A) := R(A)==R(A+1) (Syms[B]=:==,C=1)*\/ int a = GETARG_A(i); if (mrb_obj_eq(mrb, regs[a], regs[a+1])) { SET_TRUE_VALUE(regs[a]); } else { OP_CMP(==); } NEXT; } CASE(OP_LT) { \/* A B C R(A) := R(A)R(A+1) (Syms[B]=:>,C=1)*\/ int a = GETARG_A(i); OP_CMP(>); NEXT; } CASE(OP_GE) { \/* A B C R(A) := R(A)>=R(A+1) (Syms[B]=:>=,C=1)*\/ int a = GETARG_A(i); OP_CMP(>=); NEXT; } CASE(OP_ARRAY) { \/* A B C R(A) := ary_new(R(B),R(B+1)..R(B+C)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value v = mrb_ary_new_from_values(mrb, c, ®s[b]); regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYCAT) { \/* A B mrb_ary_concat(R(A),R(B)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); mrb_value splat = mrb_ary_splat(mrb, regs[b]); mrb_ary_concat(mrb, regs[a], splat); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYPUSH) { \/* A B R(A).push(R(B)) *\/ int a = GETARG_A(i); int b = GETARG_B(i); mrb_ary_push(mrb, regs[a], regs[b]); NEXT; } CASE(OP_AREF) { \/* A B C R(A) := R(B)[C] *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value v = regs[b]; if (!mrb_array_p(v)) { if (c == 0) { regs[a] = v; } else { SET_NIL_VALUE(regs[a]); } } else { v = mrb_ary_ref(mrb, v, c); regs[a] = v; } NEXT; } CASE(OP_ASET) { \/* A B C R(B)[C] := R(A) *\/ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_ary_set(mrb, regs[b], c, regs[a]); NEXT; } CASE(OP_APOST) { \/* A B C *R(A),R(A+1)..R(A+C) := R(A) *\/ int a = GETARG_A(i); mrb_value v = regs[a]; int pre = GETARG_B(i); int post = GETARG_C(i); struct RArray *ary; int len, idx; if (!mrb_array_p(v)) { v = mrb_ary_new_from_values(mrb, 1, ®s[a]); } ary = mrb_ary_ptr(v); len = (int)ARY_LEN(ary); if (len > pre + post) { v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre); regs[a++] = v; while (post--) { regs[a++] = ARY_PTR(ary)[len-post-1]; } } else { v = mrb_ary_new_capa(mrb, 0); regs[a++] = v; for (idx=0; idx+prereps[b]; if (c & OP_L_CAPTURE) { p = mrb_closure_new(mrb, nirep); } else { p = mrb_proc_new(mrb, nirep); p->flags |= MRB_PROC_SCOPE; } if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT; regs[a] = mrb_obj_value(p); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_OCLASS) { \/* A R(A) := ::Object *\/ regs[GETARG_A(i)] = mrb_obj_value(mrb->object_class); NEXT; } CASE(OP_CLASS) { \/* A B R(A) := newclass(R(A),Syms(B),R(A+1)) *\/ struct RClass *c = 0, *baseclass; int a = GETARG_A(i); mrb_value base, super; mrb_sym id = syms[GETARG_B(i)]; base = regs[a]; super = regs[a+1]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); base = mrb_obj_value(baseclass); } c = mrb_vm_define_class(mrb, base, super, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_MODULE) { \/* A B R(A) := newmodule(R(A),Syms(B)) *\/ struct RClass *c = 0, *baseclass; int a = GETARG_A(i); mrb_value base; mrb_sym id = syms[GETARG_B(i)]; base = regs[a]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); base = mrb_obj_value(baseclass); } c = mrb_vm_define_module(mrb, base, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EXEC) { \/* A Bx R(A) := blockexec(R(A),SEQ[Bx]) *\/ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_callinfo *ci; mrb_value recv = regs[a]; struct RProc *p; mrb_irep *nirep = irep->reps[bx]; \/* prepare closure *\/ p = mrb_proc_new(mrb, nirep); p->c = NULL; mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc); MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv)); p->flags |= MRB_PROC_SCOPE; \/* prepare call stack *\/ ci = cipush(mrb); ci->pc = pc + 1; ci->acc = a; ci->mid = 0; ci->stackent = mrb->c->stack; ci->argc = 0; ci->target_class = mrb_class_ptr(recv); \/* prepare stack *\/ mrb->c->stack += a; \/* setup block to call *\/ ci->proc = p; irep = p->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, ci->nregs); stack_clear(regs+1, ci->nregs-1); pc = irep->iseq; JUMP; } CASE(OP_METHOD) { \/* A B R(A).newmethod(Syms(B),R(A+1)) *\/ int a = GETARG_A(i); struct RClass *c = mrb_class_ptr(regs[a]); struct RProc *p = mrb_proc_ptr(regs[a+1]); mrb_method_t m; MRB_METHOD_FROM_PROC(m, p); mrb_define_method_raw(mrb, c, syms[GETARG_B(i)], m); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_SCLASS) { \/* A B R(A) := R(B).singleton_class *\/ int a = GETARG_A(i); int b = GETARG_B(i); regs[a] = mrb_singleton_class(mrb, regs[b]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_TCLASS) { \/* A R(A) := target_class *\/ if (!mrb->c->ci->target_class) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, \"no target class or module\"); mrb_exc_set(mrb, exc); goto L_RAISE; } regs[GETARG_A(i)] = mrb_obj_value(mrb->c->ci->target_class); NEXT; } CASE(OP_RANGE) { \/* A B C R(A) := range_new(R(B),R(B+1),C) *\/ int b = GETARG_B(i); mrb_value val = mrb_range_new(mrb, regs[b], regs[b+1], GETARG_C(i)); regs[GETARG_A(i)] = val; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_DEBUG) { \/* A B C debug print R(A),R(B),R(C) *\/ #ifdef MRB_ENABLE_DEBUG_HOOK mrb->debug_op_hook(mrb, irep, pc, regs); #else #ifndef MRB_DISABLE_STDIO printf(\"OP_DEBUG %d %d %d\\n\", GETARG_A(i), GETARG_B(i), GETARG_C(i)); #else abort(); #endif #endif NEXT; } CASE(OP_STOP) { \/* stop VM *\/ L_STOP: while (mrb->c->eidx > 0) { ecall(mrb); } ERR_PC_CLR(mrb); mrb->jmp = prev_jmp; if (mrb->exc) { return mrb_obj_value(mrb->exc); } return regs[irep->nlocals]; } CASE(OP_ERR) { \/* Bx raise RuntimeError with message Lit(Bx) *\/ mrb_value msg = mrb_str_dup(mrb, pool[GETARG_Bx(i)]); mrb_value exc; if (GETARG_A(i) == 0) { exc = mrb_exc_new_str(mrb, E_RUNTIME_ERROR, msg); } else { exc = mrb_exc_new_str(mrb, E_LOCALJUMP_ERROR, msg); } ERR_PC_SET(mrb, pc); mrb_exc_set(mrb, exc); goto L_RAISE; } } END_DISPATCH; #undef regs } MRB_CATCH(&c_jmp) { exc_catched = TRUE; goto RETRY_TRY_BLOCK; } MRB_END_EXC(&c_jmp); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":519307,"input":"void show_elog_list(LOGBOOK *lbs, int past_n, int last_n, int page_n, BOOL default_page, char *info) { int i, j, n, index, size, status, d1, m1, y1, h1, n1, c1, d2, m2, y2, h2, n2, c2, n_line, flags, printable, n_logbook, n_display, reverse, numeric, n_attr_disp, n_msg, search_all, message_id, n_page, i_start, i_stop, in_reply_to_id, page_mid, page_mid_head, level, refresh, disp_attr_flags[MAX_N_ATTR + 4]; char date[80], attrib[MAX_N_ATTR][NAME_LENGTH], disp_attr[MAX_N_ATTR + 4][NAME_LENGTH], *list, *text, *text1, in_reply_to[80], reply_to[MAX_REPLY_TO * 10], attachment[MAX_ATTACHMENTS][MAX_PATH_LENGTH], encoding[80], locked_by[256], str[NAME_LENGTH], ref[256], img[80], comment[NAME_LENGTH], mode[80], mid[80], menu_str[1000], menu_item[MAX_N_LIST][NAME_LENGTH], param[NAME_LENGTH], format[80], sort_attr[MAX_N_ATTR + 4][NAME_LENGTH], mode_cookie[80], charset[25], sort_item[NAME_LENGTH], refr[80], str2[80], draft[256]; char *p, *pt1, *pt2, *slist, *svalue, *gattr, line[1024], iattr[256]; BOOL show_attachments, threaded, csv, xml, raw, mode_commands, expand, filtering, date_filtering, disp_filter, show_text, text_in_attr, searched, found, disp_attr_link[MAX_N_ATTR + 4], sort_attributes, show_att_column = 0; time_t ltime, ltime_start, ltime_end, now, ltime1, ltime2, entry_ltime; struct tm tms, *ptms; MSG_LIST *msg_list; LOGBOOK *lbs_cur; regex_t re_buf[MAX_N_ATTR + 1]; regmatch_t pmatch[10]; \/* redirect if empty parameters *\/ if (strstr(_cmdline, \"=&\")) { while ((pt1 = strstr(_cmdline, \"=&\")) != NULL) { pt2 = pt1; while (*pt1 != '&' && *pt1 != '?') pt1--; pt1++; strcpy(param, pt1); param[pt2 - pt1] = 0; memmove(pt1, pt2 + 2, strlen(pt2 + 2) + 1); \/* remove param from lastcmd if present *\/ if ((pt1 = strstr(_cmdline, \"lastcmd=\")) != NULL) { sprintf(str, \"%s%%3D\", param); if ((pt1 = strstr(_cmdline, str)) != NULL) { pt2 = pt1 + strlen(str); while (*pt2 && *pt2 != '%') pt2++; if (*pt2 == '%') pt2 += 3; memmove(pt1, pt2, strlen(pt2) + 1); } } } if (_cmdline[strlen(_cmdline) - 1] == '=') { pt1 = _cmdline + strlen(_cmdline) - 1; while (*pt1 != '&' && *pt1 != '?') pt1--; pt1++; strcpy(param, pt1); if (param[strlen(param) - 1] == '=') param[strlen(param) - 1] = 0; *pt1 = 0; \/* remove param from lastcmd if present *\/ if ((pt1 = strstr(_cmdline, \"lastcmd=\")) != NULL) { sprintf(str, \"%s%%3D\", param); if ((pt1 = strstr(_cmdline, str)) != NULL) { pt2 = pt1 + strlen(str); while (*pt2 && *pt2 != '%' && *pt2 != '&') pt2++; if (*pt2 == '%') pt2 += 3; memmove(pt1, pt2, strlen(pt2) + 1); } } } if (_cmdline[strlen(_cmdline) - 1] == '&') _cmdline[strlen(_cmdline) - 1] = 0; redirect(lbs, _cmdline); return; } \/* redirect \"go\" command *\/ if (isparam(\"lastcmd\")) { strlcpy(str, getparam(\"lastcmd\"), sizeof(str)); url_decode(str); \/* subsitute \"last\" in command line from new parameter *\/ if (isparam(\"last\")) { if (strieq(getparam(\"last\"), \"_all_\")) subst_param(str, sizeof(str), \"last\", \"\"); else subst_param(str, sizeof(str), \"last\", getparam(\"last\")); } \/* subsitute attributes in command line from new parameter *\/ for (i = 0; i < MAX_N_ATTR; i++) if (isparam(attr_list[i])) { if (strieq(getparam(attr_list[i]), \"_all_\")) subst_param(str, sizeof(str), attr_list[i], \"\"); else subst_param(str, sizeof(str), attr_list[i], getparam(attr_list[i])); } \/* do the same for subtext *\/ if (isparam(\"subtext\")) subst_param(str, sizeof(str), \"subtext\", getparam(\"subtext\")); redirect(lbs, str); return; } \/* remove remaining \"_all_\" in parameters *\/ if (isparam(\"last\") && strieq(getparam(\"last\"), \"_all_\")) { strlcpy(str, _cmdline, sizeof(str)); subst_param(str, sizeof(str), \"last\", \"\"); redirect(lbs, str); return; } \/* remove remaining \"_all_\" or empty or \"--++--\" parameters *\/ strlcpy(str, _cmdline, sizeof(str)); found = 0; for (i = 0; i < MAX_N_ATTR; i++) { if (isparam(attr_list[i])) { if (strieq(getparam(attr_list[i]), \"_all_\")) { subst_param(str, sizeof(str), attr_list[i], \"\"); found = 1; } if (*getparam(attr_list[i]) == 0) { subst_param(str, sizeof(str), attr_list[i], \"\"); found = 1; } sprintf(ref, \"-- %s --\", attr_list[i]); if (strieq(getparam(attr_list[i]), ref)) { subst_param(str, sizeof(str), attr_list[i], \"\"); found = 1; } } } if (isparam(\"subtext\")) { if (*getparam(\"subtext\") == 0) { subst_param(str, sizeof(str), \"subtext\", \"\"); found = 1; } sprintf(ref, \"-- %s --\", loc(\"Text\")); if (strieq(getparam(\"subtext\"), ref)) { subst_param(str, sizeof(str), \"subtext\", \"\"); found = 1; } } if (found) { redirect(lbs, str); return; } slist = (char *) xmalloc((MAX_N_ATTR + 10) * NAME_LENGTH); svalue = (char *) xmalloc((MAX_N_ATTR + 10) * NAME_LENGTH); gattr = (char *) xmalloc(MAX_N_ATTR * NAME_LENGTH); list = (char *) xmalloc(10000); printable = isparam(\"Printable\") ? atoi(getparam(\"Printable\")) : 0; \/* in printable mode, display all pages *\/ if (printable) page_n = -1; if (isparam(\"Reverse\")) reverse = atoi(getparam(\"Reverse\")); else { reverse = 0; if (getcfg(lbs->name, \"Reverse sort\", str, sizeof(str))) reverse = atoi(str); } \/* get message ID from \"list\" command *\/ if (isparam(\"id\")) page_mid = atoi(getparam(\"id\")); else page_mid = 0; page_mid_head = 0; \/* default mode *\/ strlcpy(mode, \"Summary\", sizeof(mode)); show_attachments = FALSE; \/* check for valid page_n *\/ if (page_n < -1) page_n = 0; if (past_n || last_n || page_n || page_mid || default_page) { \/* for page display, get mode from config file *\/ if (getcfg(lbs->name, \"Display Mode\", str, sizeof(str))) strlcpy(mode, str, sizeof(mode)); \/* supersede mode from cookie *\/ if (isparam(\"elmode\")) strlcpy(mode, getparam(\"elmode\"), sizeof(mode)); \/* supersede mode from direct parameter *\/ if (isparam(\"mode\")) strlcpy(mode, getparam(\"mode\"), sizeof(mode)); } else { \/* for find result, get mode from find form *\/ if (isparam(\"mode\")) strlcpy(mode, getparam(\"mode\"), sizeof(mode)); else strlcpy(mode, \"Full\", sizeof(mode)); } \/* set cookie if mode changed *\/ mode_cookie[0] = 0; if (strieq(mode, \"Summary\") || strieq(mode, \"Full\") || strieq(mode, \"Threaded\")) { if (!isparam(\"elmode\") || !strieq(getparam(\"elmode\"), mode)) sprintf(mode_cookie, \"elmode=%s\", mode); } threaded = strieq(mode, \"threaded\"); csv = strieq(mode, \"CSV1\") || strieq(mode, \"CSV2\") || strieq(mode, \"CSV3\"); xml = strieq(mode, \"XML\"); raw = strieq(mode, \"Raw\"); if (csv || xml || raw) { page_n = -1; \/* display all pages *\/ show_attachments = FALSE; \/* hide attachments *\/ } \/* show attachments in full mode by default *\/ if (strieq(mode, \"Full\")) show_attachments = TRUE; \/* supersede attachment mode if in cookie *\/ if (isparam(\"elattach\")) show_attachments = atoi(getparam(\"elattach\")); \/* supersede attachment mode if in parameter *\/ if (isparam(\"attach\")) show_attachments = atoi(getparam(\"attach\")); \/* set cookie if attachment mode changed in full view *\/ if (mode_cookie[0] == 0 && strieq(mode, \"Full\")) { if (!isparam(\"elattach\") || atoi(getparam(\"elattach\")) != show_attachments) sprintf(mode_cookie, \"elattach=%d\", show_attachments); } \/*---- convert dates to ltime ----*\/ time(&now); ptms = localtime(&now); assert(ptms); ltime_end = ltime_start = 0; d1 = m1 = y1 = h1 = n1 = c1 = d2 = m2 = y2 = h2 = n2 = c2 = 0; if (!past_n && !last_n) { ltime_start = retrieve_date(\"a\", TRUE); if (ltime_start < 0) { xfree(slist); xfree(svalue); xfree(gattr); xfree(list); return; } if (ltime_start) { memcpy(&tms, localtime(<ime_start), sizeof(struct tm)); y1 = tms.tm_year + 1900; m1 = tms.tm_mon + 1; d1 = tms.tm_mday; h1 = tms.tm_hour; n1 = tms.tm_min; c1 = tms.tm_sec; } ltime_end = retrieve_date(\"b\", FALSE); if (ltime_end < 0) { xfree(slist); xfree(svalue); xfree(gattr); xfree(list); return; } if (ltime_end) { if (ltime_end <= ltime_start) { sprintf(str, \"Error: Start date after end date\"); show_error(str); xfree(slist); xfree(svalue); xfree(gattr); xfree(list); return; } memcpy(&tms, localtime(<ime_end), sizeof(struct tm)); y2 = tms.tm_year + 1900; m2 = tms.tm_mon + 1; d2 = tms.tm_mday; h2 = tms.tm_hour; n2 = tms.tm_min; c2 = tms.tm_sec; } } if (ltime_start && ltime_end && ltime_start > ltime_end) { show_error(loc(\"Error: start date after end date\")); xfree(slist); xfree(svalue); xfree(gattr); xfree(list); return; } \/*---- if user present but not allowed, log it out (required when several logbooks are used with different access rights and global passwords ----*\/ if (isparam(\"unm\") && !check_login_user(lbs, getparam(\"unm\"))) { unsetparam(\"unm\"); sid_remove(getparam(\"sid\")); set_sid_cookie(lbs, \"\", \"\"); } \/*---- apply last login cut ----*\/ if (isparam(\"new_entries\") && atoi(getparam(\"new_entries\")) == 1 && isparam(\"unm\")) get_user_line(lbs, getparam(\"unm\"), NULL, NULL, NULL, NULL, <ime_start, NULL); \/*---- assemble message list ----*\/ \/* check for search all *\/ search_all = isparam(\"all\") ? atoi(getparam(\"all\")) : 0; if (getcfg(lbs->name, \"Search all logbooks\", str, sizeof(str)) && atoi(str) == 0) search_all = 0; n_msg = 0; n_display = 0; if (search_all) { \/* count logbooks *\/ for (n_logbook = 0;; n_logbook++) { if (!lb_list[n_logbook].name[0]) break; if (lbs->top_group[0] && !strieq(lbs->top_group, lb_list[n_logbook].top_group)) continue; if (isparam(\"unm\") && !check_login_user(&lb_list[n_logbook], getparam(\"unm\"))) continue; n_msg += *lb_list[n_logbook].n_el_index; } } else { n_logbook = 1; n_msg = *lbs->n_el_index; } msg_list = (MSG_LIST *) xmalloc(sizeof(MSG_LIST) * n_msg); lbs_cur = lbs; numeric = TRUE; for (i = n = 0; i < n_logbook; i++) { if (search_all) lbs_cur = &lb_list[i]; if (lbs->top_group[0] && !strieq(lbs->top_group, lbs_cur->top_group)) continue; if (isparam(\"unm\") && !check_login_user(lbs_cur, getparam(\"unm\"))) continue; for (j = 0; j < *lbs_cur->n_el_index; j++) { msg_list[n].lbs = lbs_cur; msg_list[n].index = j; msg_list[n].number = (int) lbs_cur->el_index[j].file_time; msg_list[n].in_reply_to = lbs_cur->el_index[j].in_reply_to; n++; } } \/*---- apply start\/end date cut ----*\/ date_filtering = FALSE; if (past_n > 0) ltime_start = now - 3600 * 24 * past_n; \/\/ past n days else if (past_n < 0) ltime_start = now + 3600 * past_n; \/\/ past n hours if (last_n && last_n < n_msg) { date_filtering = TRUE; for (i = n_msg - last_n - 1; i >= 0; i--) msg_list[i].lbs = NULL; } if (ltime_start) { date_filtering = TRUE; for (i = 0; i < n_msg; i++) if (msg_list[i].lbs && msg_list[i].lbs->el_index[msg_list[i].index].file_time < ltime_start) msg_list[i].lbs = NULL; } if (ltime_end) { date_filtering = TRUE; for (i = 0; i < n_msg; i++) if (msg_list[i].lbs && msg_list[i].lbs->el_index[msg_list[i].index].file_time > ltime_end) msg_list[i].lbs = NULL; } if (isparam(\"last\") || getcfg(lbs->name, \"Last default\", str, sizeof(str))) { date_filtering = TRUE; if (isparam(\"last\")) n = atoi(getparam(\"last\")); else n = atoi(str); if (n > 0) { for (i = 0; i < n_msg; i++) if (msg_list[i].lbs && msg_list[i].lbs->el_index[msg_list[i].index].file_time < now - 3600 * 24 * n) msg_list[i].lbs = NULL; } } \/*---- filter message list ----*\/ filtering = FALSE; show_text = TRUE; searched = found = FALSE; for (i = 0; i < lbs->n_attr; i++) { \/* check if attribute filter *\/ if (isparam(attr_list[i])) break; if (attr_flags[i] & (AF_DATE | AF_DATETIME)) { sprintf(str, \"%da\", i); if (retrieve_date(str, TRUE)) break; sprintf(str, \"%db\", i); if (retrieve_date(str, TRUE)) break; } if (attr_flags[i] & AF_MULTI) { for (j = 0; j < MAX_N_LIST && attr_options[i][j][0]; j++) { sprintf(str, \"%s_%d\", attr_list[i], j); if (isparam(str)) { filtering = TRUE; break; } } } if (attr_flags[i] & (AF_MUSERLIST | AF_MUSEREMAIL)) { for (j = 0; j < MAX_N_LIST; j++) { sprintf(str, \"%s_%d\", attr_list[i], j); if (isparam(str)) { filtering = TRUE; break; } } } \/* check if sort by attribute *\/ if ((isparam(\"sort\") && strieq(getparam(\"sort\"), attr_list[i])) || (isparam(\"rsort\") && strieq(getparam(\"rsort\"), attr_list[i]))) break; } \/* turn on filtering if found *\/ if (i < lbs->n_attr) filtering = TRUE; if (isparam(\"subtext\")) filtering = TRUE; if (getcfg(lbs->name, \"Sort Attributes\", list, 10000)) filtering = TRUE; text = (char *) xmalloc(TEXT_SIZE); text1 = (char *) xmalloc(TEXT_SIZE); \/* prepare for regex search *\/ memset(re_buf, 0, sizeof(re_buf)); \/* compile regex for subtext *\/ if (isparam(\"subtext\")) { strlcpy(str, getparam(\"subtext\"), sizeof(str)); flags = REG_EXTENDED; if (!isparam(\"casesensitive\")) flags |= REG_ICASE; status = regcomp(re_buf, str, flags); if (status) { sprintf(line, loc(\"Error in regular expression \\\"%s\\\"\"), str); strlcat(line, \": \", sizeof(line)); regerror(status, re_buf, str, sizeof(str)); strlcat(line, str, sizeof(line)); strencode2(str, line, sizeof(str)); show_error(str); return; } } \/* compile regex for attributes *\/ for (i = 0; i < lbs->n_attr; i++) { if (isparam(attr_list[i])) { strlcpy(str, getparam(attr_list[i]), sizeof(str)); \/* if value starts with '$', substitute it *\/ if (str[0] == '$') { j = build_subst_list(lbs, (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, attrib, TRUE); add_subst_time(lbs, (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, \"entry time\", date, &j, 0); strsubst_list(str, sizeof(str), (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, j); setparam(attr_list[i], str); } flags = REG_EXTENDED; if (!isparam(\"casesensitive\")) flags |= REG_ICASE; status = regcomp(re_buf + i + 1, str, flags); if (status) { sprintf(line, loc(\"Error in regular expression \\\"%s\\\"\"), str); strlcat(line, \": \", sizeof(line)); regerror(status, re_buf + i + 1, str, sizeof(str)); strlcat(line, str, sizeof(line)); strencode2(str, line, sizeof(str)); show_error(str); return; } } } sort_item[0] = 0; if (isparam(\"sort\")) strlcpy(sort_item, getparam(\"sort\"), sizeof(sort_item)); if (isparam(\"rsort\")) strlcpy(sort_item, getparam(\"rsort\"), sizeof(sort_item)); sort_attributes = getcfg(lbs->name, \"Sort Attributes\", str, sizeof(str)); \/* do filtering *\/ for (index = 0; index < n_msg; index++) { if (!msg_list[index].lbs) continue; \/* retrieve message *\/ size = TEXT_SIZE; message_id = msg_list[index].lbs->el_index[msg_list[index].index].message_id; if (filtering) { status = el_retrieve(msg_list[index].lbs, message_id, date, attr_list, attrib, lbs->n_attr, text, &size, in_reply_to, reply_to, attachment, encoding, locked_by, draft); if (status != EL_SUCCESS) break; \/* apply filter for attributes *\/ for (i = 0; i < lbs->n_attr; i++) { \/* replace icon name with their comments if present *\/ if (attr_flags[i] & AF_ICON) { sprintf(str, \"Icon comment %s\", attrib[i]); if (getcfg(lbs->name, str, comment, sizeof(comment))) strlcpy(attrib[i], comment, NAME_LENGTH); } \/* check for multi attributes *\/ if (attr_flags[i] & AF_MULTI) { \/* OR of any of the values *\/ searched = found = FALSE; for (j = 0; j < MAX_N_LIST && attr_options[i][j][0]; j++) { sprintf(str, \"%s_%d\", attr_list[i], j); if (isparam(str)) { searched = TRUE; if (strstr(attrib[i], getparam(str))) { found = TRUE; break; } } } \/* search for parameter without '_' coming from quick filter *\/ if (isparam(attr_list[i])) { searched = TRUE; strlcpy(str, getparam(attr_list[i]), sizeof(str)); if (str[0] == '^' && str[strlen(str) - 1] == '$') { str[strlen(str) - 1] = 0; strlcpy(comment, str + 1, NAME_LENGTH); } else strlcpy(comment, str, NAME_LENGTH); strlcpy(str, comment, sizeof(str)); if (strstr(attrib[i], str)) found = TRUE; } if (searched && !found) break; } \/* check for multi user list or multi user email *\/ else if (attr_flags[i] & (AF_MUSERLIST | AF_MUSEREMAIL)) { \/* OR of any of the values *\/ searched = found = FALSE; for (j = 0; j < MAX_N_LIST; j++) { sprintf(str, \"%s_%d\", attr_list[i], j); if (isparam(str)) { searched = TRUE; if (strstr(attrib[i], getparam(str))) { found = TRUE; break; } } } \/* search for parameter without '_' coming from quick filter *\/ if (isparam(attr_list[i])) { searched = TRUE; if (strstr(attrib[i], getparam(attr_list[i]))) found = TRUE; } if (searched && !found) break; } else if (attr_flags[i] & (AF_DATE | AF_DATETIME)) { \/* check for last[i]\/next[i] *\/ ltime = isparam(attr_list[i]) ? atoi(getparam(attr_list[i])) : 0; \/* today 12h noon *\/ time(&now); memcpy(&tms, localtime(&now), sizeof(struct tm)); tms.tm_hour = 12; tms.tm_min = 0; tms.tm_sec = 0; now = mktime(&tms); \/* negative i: last [i] days *\/ if (ltime < 0) if (atoi(attrib[i]) < now + ltime * 3600 * 24 - 3600 * 12 || atoi(attrib[i]) > now) break; \/* positive i: next [i] days *\/ if (ltime > 0) if (atoi(attrib[i]) > now + ltime * 3600 * 24 + 3600 * 12 || atoi(attrib[i]) < now) break; \/* check for start date \/ end date *\/ sprintf(str, \"%da\", i); ltime = retrieve_date(str, TRUE); if (ltime > 0 && atoi(attrib[i]) < ltime) break; sprintf(str, \"%db\", i); ltime = retrieve_date(str, FALSE); if (ltime > 0 && (atoi(attrib[i]) > ltime || atoi(attrib[i]) == 0)) break; } else { strlcpy(str, isparam(attr_list[i]) ? getparam(attr_list[i]) : \"\", sizeof(str)); \/* if value starts with '$', substitute it *\/ if (str[0] == '$') { j = build_subst_list(lbs, (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, attrib, TRUE); sprintf(mid, \"%d\", message_id); add_subst_list((char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, \"message id\", mid, &j); add_subst_time(lbs, (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, \"entry time\", date, &j, 0); strsubst_list(str, sizeof(str), (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, j); setparam(attr_list[i], str); } if (isparam(attr_list[i])) { status = regexec(re_buf + 1 + i, attrib[i], 10, pmatch, 0); if (status == REG_NOMATCH) break; } } } if (i < lbs->n_attr) { msg_list[index].lbs = NULL; continue; } if (isparam(\"subtext\")) { status = regexec(re_buf, text, 10, pmatch, 0); if (isparam(\"sall\") && atoi(getparam(\"sall\")) && status == REG_NOMATCH) { \/\/ search text in attributes for (i = 0; i < lbs->n_attr; i++) { status = regexec(re_buf, attrib[i], 10, pmatch, 0); if (status != REG_NOMATCH) break; } if (i == lbs->n_attr) { msg_list[index].lbs = NULL; continue; } } else if (status == REG_NOMATCH) { msg_list[index].lbs = NULL; continue; } } } \/\/ if (filtering) \/* evaluate \"sort attributes\" *\/ if (sort_attributes) { getcfg(lbs->name, \"Sort Attributes\", list, 10000); msg_list[index].string[0] = 0; n = strbreak(list, sort_attr, MAX_N_ATTR, \",\", FALSE); for (i = 0; i < n; i++) { for (j = 0; j < lbs->n_attr; j++) { if (strieq(sort_attr[i], attr_list[j])) { strlcat(msg_list[index].string, \" \", sizeof(msg_list[index].string)); strlcat(msg_list[index].string, attrib[j], sizeof(msg_list[index].string)); if (attr_flags[i] & (AF_NUMERIC | AF_DATETIME | AF_DATE)) { msg_list[index].number = atoi(attrib[j]); numeric = TRUE; } else numeric = FALSE; break; } } if (strieq(sort_attr[i], loc(\"ID\"))) { strlcat(msg_list[index].string, \" \", sizeof(msg_list[index].string)); sprintf(str, \"%08d\", message_id); strlcat(msg_list[index].string, str, sizeof(msg_list[index].string)); } else if (strieq(sort_attr[i], loc(\"Logbook\"))) { strlcat(msg_list[index].string, \" \", sizeof(msg_list[index].string)); strlcat(msg_list[index].string, msg_list[index].lbs->name, sizeof(msg_list[index].string)); } else if (strieq(sort_attr[i], loc(\"Date\"))) { strlcat(msg_list[index].string, \" \", sizeof(msg_list[index].string)); entry_ltime = date_to_ltime(date); sprintf(str, \"%08d\", (int) entry_ltime); strlcat(msg_list[index].string, str, sizeof(msg_list[index].string)); } } } \/* add attribute for sorting *\/ if (sort_item[0]) { for (i = 0; i < lbs->n_attr; i++) { if (strieq(sort_item, attr_list[i])) { if (attr_flags[i] & (AF_NUMERIC | AF_DATETIME | AF_DATE)) { numeric = TRUE; msg_list[index].number = atoi(attrib[i]); } else { numeric = FALSE; strlcpy(msg_list[index].string, attrib[i], 256); } } if (strieq(sort_item, loc(\"ID\"))) { numeric = TRUE; msg_list[index].number = message_id; } if (strieq(sort_item, loc(\"Logbook\"))) strlcpy(msg_list[index].string, msg_list[index].lbs->name, 256); } if (isparam(\"rsort\")) reverse = 1; if (isparam(\"sort\")) reverse = 0; } } \/*---- in threaded mode, set date of latest entry of thread ----*\/ if (threaded && !filtering && !date_filtering) { for (index = 0; index < n_msg; index++) { if (!msg_list[index].lbs) continue; message_id = msg_list[index].lbs->el_index[msg_list[index].index].message_id; in_reply_to_id = msg_list[index].lbs->el_index[msg_list[index].index].in_reply_to; if (!in_reply_to_id) continue; do { message_id = in_reply_to_id; \/* search index of message *\/ for (i = 0; i < *msg_list[index].lbs->n_el_index; i++) if (msg_list[index].lbs->el_index[i].message_id == message_id) break; \/* stop if not found *\/ if (i == *msg_list[index].lbs->n_el_index) break; in_reply_to_id = msg_list[index].lbs->el_index[i].in_reply_to; } while (in_reply_to_id); \/* if head not found, skip message *\/ if (i == *msg_list[index].lbs->n_el_index) { msg_list[index].lbs = NULL; continue; } \/* set new page message ID with head message *\/ if (page_mid && msg_list[index].lbs->el_index[msg_list[index].index].message_id == page_mid) page_mid_head = message_id; \/* search message head in list *\/ for (j = 0; j < n_msg; j++) if (msg_list[j].lbs == msg_list[index].lbs && msg_list[j].index == i) break; if (j < index) { \/* set date from current message, if later *\/ if (msg_list[j].number < msg_list[index].number) msg_list[j].number = msg_list[index].number; } \/* now delete current message, to leave only heads in list *\/ msg_list[index].lbs = NULL; } } \/*---- compact messasges ----*\/ for (i = j = 0; i < n_msg; i++) if (msg_list[i].lbs) memcpy(&msg_list[j++], &msg_list[i], sizeof(MSG_LIST)); n_msg = j; \/*---- sort messasges ----*\/ if (numeric) qsort(msg_list, n_msg, sizeof(MSG_LIST), reverse ? msg_compare_reverse_numeric : msg_compare_numeric); else qsort(msg_list, n_msg, sizeof(MSG_LIST), reverse ? msg_compare_reverse : msg_compare); \/*---- search page for specific message ----*\/ if (getcfg(lbs->name, \"Entries per page\", str, sizeof(str))) n_page = atoi(str); else n_page = 20; if (isparam(\"npp\")) { n_page = atoi(getparam(\"npp\")); if (n_page < 1) n_page = 1; if (n_page > 100000) n_page = 100000; } if (page_mid) { default_page = 0; for (i = 0; i < n_msg; i++) if (msg_list[i].lbs->el_index[msg_list[i].index].message_id == page_mid || msg_list[i].lbs->el_index[msg_list[i].index].message_id == page_mid_head) break; if (i < n_msg) page_n = i \/ n_page + 1; } \/*---- number of messages per page ----*\/ n_attr_disp = n_line = 0; i_start = 0; i_stop = n_msg - 1; if (!csv && !xml && !raw) { if (page_n || default_page) { if (default_page && page_n != -1) page_n = reverse ? 1 : (n_msg - 1) \/ n_page + 1; if (page_n != -1) { i_start = (page_n - 1) * n_page; i_stop = i_start + n_page - 1; if (i_start >= n_msg && n_msg > 0) { page_n = 1; i_start = 0; } if (i_stop >= n_msg) i_stop = n_msg - 1; } } } \/*---- header ----*\/ if (getcfg(lbs->name, \"List Page Title\", str, sizeof(str))) { i = build_subst_list(lbs, (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, NULL, TRUE); strsubst_list(str, sizeof(str), (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, i); strip_html(str); } else sprintf(str, \"ELOG %s\", lbs->name); if (csv) { \/* no menus and tables *\/ show_plain_header(0, \"export.csv\"); rsprintf(\"\\\"%s\\\"\", loc(\"Message ID\")); if (strieq(mode, \"CSV1\")) rsprintf(\",\"); else rsprintf(\";\"); rsprintf(\"\\\"%s\\\"\", loc(\"Date\")); if (strieq(mode, \"CSV1\")) rsprintf(\",\"); else rsprintf(\";\"); for (i = 0; i < lbs->n_attr; i++) { strlcpy(str, attr_list[i], sizeof(str)); if (str[0]) { rsputs(\"\\\"\"); pt1 = str; while ((pt2 = strchr(pt1, '\"')) != NULL) { *pt2 = 0; rsputs(pt1); rsputs(\"\\\"\\\"\"); pt1 = pt2 + 1; } rsputs(pt1); rsputs(\"\\\"\"); } if (i < lbs->n_attr - 1) { if (strieq(mode, \"CSV1\")) rsprintf(\",\"); else rsprintf(\";\"); } else { if (strieq(mode, \"CSV3\")) rsprintf(\";\\\"Text\\\"\"); rsprintf(\"\\r\\n\"); } } } else if (xml) { \/* no menus and tables *\/ show_plain_header(0, \"export.xml\"); if (!getcfg(\"global\", \"charset\", charset, sizeof(charset))) strcpy(charset, DEFAULT_HTTP_CHARSET); rsprintf(\"\\n\", charset); rsprintf(\"\\n\", VERSION); rsprintf(\"\\n\"); } else if (raw) { \/* no menus and tables *\/ show_plain_header(0, \"export.txt\"); } else { if (getcfg(lbs->name, \"Refresh\", refr, sizeof(refr))) refresh = atoi(refr); else refresh = 0; show_standard_header(lbs, TRUE, str, NULL, TRUE, mode_cookie, NULL, refresh); \/*---- title ----*\/ strlcpy(str, \", \", sizeof(str)); if (past_n == 1) strcat(str, loc(\"Last day\")); else if (past_n > 1) sprintf(str + strlen(str), loc(\"Last %d days\"), past_n); else if (past_n < 0) sprintf(str + strlen(str), loc(\"Last %d hours\"), -past_n); else if (last_n) sprintf(str + strlen(str), loc(\"Last %d entries\"), last_n); else if (page_n == -1) strlcpy(str + strlen(str), loc(\"all entries\"), sizeof(str) - strlen(str)); else if (page_n) sprintf(str + strlen(str), loc(\"Page %d of %d\"), page_n, (n_msg - 1) \/ n_page + 1); if (strlen(str) == 2) str[0] = 0; if (printable) show_standard_title(lbs, str, 1); else show_standard_title(lbs, str, 0); \/*---- menu buttons ----*\/ if (!printable) { rsprintf(\"

\\n\"); \/* current command line for select command *\/ strlcpy(str, isparam(\"cmdline\") ? getparam(\"cmdline\") : \"\", sizeof(str)); \/* remove select switch *\/ if (strstr(str, \"select=1\")) { *strstr(str, \"select=1\") = 0; if (strlen(str) > 1 && (str[strlen(str) - 1] == '&' || str[strlen(str) - 1] == '?')) str[strlen(str) - 1] = 0; } \/* store current command line as hidden parameter for page navigation *\/ if (str[0] && !strieq(str, \"?\")) { rsprintf(\"\\n\", str); } if (!getcfg(lbs->name, \"Guest Find menu commands\", menu_str, sizeof(menu_str)) || logged_in(lbs)) getcfg(lbs->name, \"Find menu commands\", menu_str, sizeof(menu_str)); if (!menu_str[0]) { if (!getcfg(lbs->name, \"Guest list menu commands\", menu_str, sizeof(menu_str)) || logged_in(lbs)) getcfg(lbs->name, \"list menu commands\", menu_str, sizeof(menu_str)); } \/* default menu commands *\/ if (menu_str[0] == 0) { strlcpy(menu_str, \"New, Find, Select, Import, \", sizeof(menu_str)); if (getcfg(lbs->name, \"Password file\", str, sizeof(str))) strlcat(menu_str, \"Config, Logout, \", sizeof(menu_str)); else strlcat(menu_str, \"Config, \", sizeof(menu_str)); if (getcfg(lbs->name, \"Mirror server\", str, sizeof(str))) strlcat(menu_str, \"Synchronize, \", sizeof(menu_str)); strlcpy(str, loc(\"Last x\"), sizeof(str)); strlcat(menu_str, \"Last x, Help, \", sizeof(menu_str)); } n = strbreak(menu_str, menu_item, MAX_N_LIST, \",\", FALSE); for (i = 0; i < n; i++) { if (is_user_allowed(lbs, menu_item[i])) { if (strieq(menu_item[i], \"Last x\")) { if (past_n > 0) { sprintf(str, loc(\"Last %d days\"), past_n * 2); rsprintf(\" %s<\/a> |\\n\", past_n * 2, mode, str); } else { strlcpy(str, loc(\"Last day\"), sizeof(str)); rsprintf(\" %s<\/a> |\\n\", mode, str); } if (last_n) { sprintf(str, loc(\"Last %d entries\"), last_n * 2); rsprintf(\" %s<\/a> |\\n\", last_n * 2, mode, str); } } else if (strieq(menu_item[i], \"Select\")) { strlcpy(str, getparam(\"cmdline\"), sizeof(str)); if (isparam(\"select\") && atoi(getparam(\"select\")) == 1) { \/* remove select switch *\/ if (strstr(str, \"select=1\")) { *strstr(str, \"select=1\") = 0; if (strlen(str) > 1 && (str[strlen(str) - 1] == '&' || str[strlen(str) - 1] == '?')) str[strlen(str) - 1] = 0; } } else { \/* add select switch *\/ if (strchr(str, '?')) strcat(str, \"&select=1\"); else strcat(str, \"?select=1\"); } rsprintf(\" %s<\/a> |\\n\", loc(\"Select\")); } else { strlcpy(str, loc(menu_item[i]), sizeof(str)); url_encode(str, sizeof(str)); if (i < n - 1) rsprintf(\" %s<\/a> |\\n\", str, loc(menu_item[i])); else rsprintf(\" %s<\/a> \\n\", str, loc(menu_item[i])); } } } rsprintf(\"<\/span><\/td><\/tr>\\n\\n\"); } \/*---- list menu text ----*\/ if ((getcfg(lbs->name, \"find menu text\", str, sizeof(str)) || getcfg(lbs->name, \"list menu text\", str, sizeof(str))) && !printable) { FILE *f; char file_name[256], *buf; rsprintf(\"
\\n\"); \/* check if file starts with an absolute directory *\/ if (str[0] == DIR_SEPARATOR || str[1] == ':') strlcpy(file_name, str, sizeof(file_name)); else { strlcpy(file_name, logbook_dir, sizeof(file_name)); strlcat(file_name, str, sizeof(file_name)); } f = fopen(file_name, \"rb\"); if (f != NULL) { fseek(f, 0, SEEK_END); size = TELL(fileno(f)); fseek(f, 0, SEEK_SET); buf = (char *) xmalloc(size + 1); fread(buf, 1, size, f); buf[size] = 0; fclose(f); rsputs(buf); } else rsprintf(\"
Error: file \\\"%s\\\"<\/i> not found<\/b><\/center>\", file_name); rsprintf(\"<\/span><\/td><\/tr>\"); } \/*---- display filters ----*\/ disp_filter = isparam(\"ma\") || isparam(\"ya\") || isparam(\"da\") || isparam(\"mb\") || isparam(\"yb\") || isparam(\"db\") || isparam(\"subtext\") || isparam(\"last\"); for (i = 0; i < lbs->n_attr; i++) if (isparam(attr_list[i]) && (attr_flags[i] & (AF_DATE | AF_DATETIME)) == 0) disp_filter = TRUE; for (i = 0; i < lbs->n_attr; i++) { if (attr_flags[i] & (AF_DATE | AF_DATETIME)) { sprintf(str, \"%da\", i); ltime = retrieve_date(str, TRUE); if (ltime > 0) disp_filter = TRUE; sprintf(str, \"%db\", i); ltime = retrieve_date(str, FALSE); if (ltime > 0) disp_filter = TRUE; } if (attr_flags[i] & (AF_MULTI | AF_MUSERLIST | AF_MUSEREMAIL)) { for (j = 0; j < MAX_N_LIST; j++) { sprintf(str, \"%s_%d\", attr_list[i], j); if (isparam(str)) disp_filter = TRUE; if (isparam(attr_list[i])) disp_filter = TRUE; } } } if (isparam(\"new_entries\") && atoi(getparam(\"new_entries\")) == 1) { rsprintf(\"
\\n\"); rsprintf(\"\\n\"); rsprintf(\"
%s:<\/td>\", loc(\"New entries since\")); memcpy(&tms, localtime(<ime_start), sizeof(struct tm)); my_strftime(str, sizeof(str), \"%c\", &tms); rsprintf(\"%s<\/td><\/tr>\", str); rsprintf(\"<\/table><\/td><\/tr>\\n\\n\"); } if (disp_filter) { rsprintf(\"
\\n\"); rsprintf(\"\\n\"); if (isparam(\"last\")) { rsprintf(\"
%s:<\/td>\", loc(\"Restrict search to last\")); strencode2(str, getparam(\"last\"), sizeof(str)); rsprintf(\"%s %s<\/td><\/tr>\", str, loc(\"days\")); } if (isparam(\"ma\") || isparam(\"ya\") || isparam(\"da\") || isparam(\"ha\") || isparam(\"na\") || isparam(\"ca\")) { memset(&tms, 0, sizeof(struct tm)); tms.tm_year = y1 - 1900; tms.tm_mon = m1 - 1; tms.tm_mday = d1; tms.tm_hour = h1; tms.tm_min = n1; tms.tm_sec = c1; if (tms.tm_year < 90) tms.tm_year += 100; mktime(&tms); if (!getcfg(lbs->name, \"Time format\", format, sizeof(format))) strcpy(format, DEFAULT_TIME_FORMAT); strftime(str, sizeof(str), format, &tms); rsprintf(\"
%s:<\/td>\", loc(\"Start date\")); rsprintf(\"%s<\/td><\/tr>\", str); } if (isparam(\"mb\") || isparam(\"yb\") || isparam(\"db\") || isparam(\"hb\") || isparam(\"nb\") || isparam(\"cb\")) { memset(&tms, 0, sizeof(struct tm)); tms.tm_year = y2 - 1900; tms.tm_mon = m2 - 1; tms.tm_mday = d2; tms.tm_hour = h2; tms.tm_min = n2; tms.tm_sec = c2; if (tms.tm_year < 90) tms.tm_year += 100; ltime = mktime(&tms); memcpy(&tms, localtime(<ime), sizeof(struct tm)); if (!getcfg(lbs->name, \"Time format\", format, sizeof(format))) strcpy(format, DEFAULT_TIME_FORMAT); strftime(str, sizeof(str), format, &tms); rsprintf(\"
%s:<\/td>\", loc(\"End date\")); rsprintf(\"%s<\/td><\/tr>\", str); } for (i = 0; i < lbs->n_attr; i++) { if (attr_flags[i] & (AF_DATE | AF_DATETIME)) { sprintf(str, \"%da\", i); ltime1 = retrieve_date(str, TRUE); sprintf(str, \"%db\", i); ltime2 = retrieve_date(str, TRUE); if (ltime1 > 0 || ltime2 > 0) { rsprintf(\"
%s:<\/td>\", attr_list[i]); rsprintf(\"\"); if (ltime1) { memcpy(&tms, localtime(<ime1), sizeof(struct tm)); if (attr_flags[i] & AF_DATE) strcpy(format, DEFAULT_DATE_FORMAT); else strcpy(format, DEFAULT_TIME_FORMAT); my_strftime(str, sizeof(str), format, &tms); if (ltime2 > 0) rsprintf(\"%s %s\", loc(\"From\"), str); else rsprintf(\"%s %s\", loc(\"After\"), str); } if (ltime2) { memcpy(&tms, localtime(<ime2), sizeof(struct tm)); if (attr_flags[i] & AF_DATE) strcpy(format, DEFAULT_DATE_FORMAT); else strcpy(format, DEFAULT_TIME_FORMAT); my_strftime(str, sizeof(str), format, &tms); if (ltime1 > 0) rsprintf(\" %s %s\", loc(\"to\"), str); else rsprintf(\"%s %s\", loc(\"Before\"), str); } rsprintf(\"<\/td><\/tr>\", comment); } } else if (attr_flags[i] & AF_MULTI) { line[0] = 0; for (j = 0; j < MAX_N_LIST && attr_options[i][j][0]; j++) { sprintf(iattr, \"%s_%d\", attr_list[i], j); if (isparam(iattr)) { comment[0] = 0; if (attr_flags[i] & AF_ICON) { sprintf(str, \"Icon comment %s\", getparam(iattr)); getcfg(lbs->name, str, comment, sizeof(comment)); } if (line[0]) strlcat(line, \" | \", sizeof(line)); if (comment[0] == 0) { strlcpy(str, getparam(iattr), sizeof(str)); if (str[0] == '^' && str[strlen(str) - 1] == '$') { str[strlen(str) - 1] = 0; strlcpy(comment, str + 1, NAME_LENGTH); } else strlcpy(comment, str, NAME_LENGTH); strlcpy(str, comment, sizeof(str)); strencode2(line + strlen(line), str, sizeof(line) - strlen(line)); } else strlcat(line, comment, sizeof(line)); } } if (isparam(attr_list[i])) { comment[0] = 0; if (attr_flags[i] & AF_ICON) { sprintf(str, \"Icon comment %s\", getparam(attr_list[i])); getcfg(lbs->name, str, comment, sizeof(comment)); } if (line[0]) strlcat(line, \" | \", sizeof(line)); if (comment[0] == 0) { strlcpy(str, getparam(attr_list[i]), sizeof(str)); if (str[0] == '^' && str[strlen(str) - 1] == '$') { str[strlen(str) - 1] = 0; strlcpy(comment, str + 1, NAME_LENGTH); } else strlcpy(comment, str, NAME_LENGTH); strlcpy(str, comment, sizeof(str)); strencode2(line + strlen(line), str, sizeof(line) - strlen(line)); } else strlcat(line, comment, sizeof(line)); } if (line[0]) { rsprintf(\"
%s:<\/td>\", attr_list[i]); rsprintf(\"\"); rsprintf(\"%s<\/span><\/td><\/tr>\", line); } } else if (attr_flags[i] & (AF_MUSERLIST | AF_MUSEREMAIL)) { line[0] = 0; for (j = 0; j < MAX_N_LIST; j++) { sprintf(iattr, \"%s_%d\", attr_list[i], j); if (isparam(iattr)) { if (line[0]) strlcat(line, \" | \", sizeof(line)); strlcat(line, getparam(iattr), sizeof(line)); } } if (isparam(attr_list[i])) { if (line[0]) strlcat(line, \" | \", sizeof(line)); strencode2(line + strlen(line), getparam(attr_list[i]), sizeof(line) - strlen(line)); } if (line[0]) { rsprintf(\"
%s:<\/td>\", attr_list[i]); rsprintf(\"\"); rsprintf(\"%s<\/span><\/td><\/tr>\", line); } } else if (isparam(attr_list[i])) { strlcpy(str, getparam(attr_list[i]), sizeof(str)); if (str[0] && !strieq(str, \"_all_\") && strncmp(str, \"--\", 2) != 0) { comment[0] = 0; if (attr_flags[i] & AF_ICON) { sprintf(str, \"Icon comment %s\", getparam(attr_list[i])); getcfg(lbs->name, str, comment, sizeof(comment)); } if (comment[0] == 0) { strlcpy(str, getparam(attr_list[i]), sizeof(str)); if (str[0] == '^' && str[strlen(str) - 1] == '$') { str[strlen(str) - 1] = 0; strlcpy(comment, str + 1, NAME_LENGTH); } else strlcpy(comment, str, NAME_LENGTH); strlcpy(str, comment, sizeof(str)); strencode2(comment, str, sizeof(comment)); } rsprintf(\"
%s:<\/td>\", attr_list[i]); rsprintf(\"\"); rsprintf(\"%s<\/span><\/td><\/tr>\", comment); } } } if (isparam(\"subtext\")) { rsprintf(\"
%s:<\/td>\", loc(\"Text\")); rsprintf(\"\"); strencode2(str, getparam(\"subtext\"), sizeof(str)); rsprintf(\"%s<\/span><\/td><\/tr>\", str); } rsprintf(\"<\/table><\/td><\/tr>\\n\\n\"); } \/* get number of summary lines *\/ n_line = 3; if (getcfg(lbs->name, \"Summary lines\", str, sizeof(str))) n_line = atoi(str); \/* suppress summary completely if text body is disabled *\/ if (getcfg(lbs->name, \"Show text\", str, sizeof(str)) && atoi(str) == 0) n_line = 0; \/* suppress attachment colum if switched off *\/ show_att_column = strieq(mode, \"Summary\"); if (getcfg(lbs->name, \"Enable attachments\", str, sizeof(str)) && atoi(str) == 0) show_att_column = FALSE; \/* get mode commands flag *\/ mode_commands = TRUE; if (getcfg(lbs->name, \"Mode commands\", str, sizeof(str)) && atoi(str) == 0) mode_commands = FALSE; \/*---- evaluate conditions for quick filters *\/ for (i = 0; i < lbs->n_attr; i++) { attrib[i][0] = 0; if (isparam(attr_list[i])) { strlcpy(str, getparam(attr_list[i]), sizeof(str)); if (str[0] == '^' && str[strlen(str) - 1] == '$') { str[strlen(str) - 1] = 0; strlcpy(attrib[i], str + 1, NAME_LENGTH); } else strlcpy(attrib[i], str, NAME_LENGTH); } } evaluate_conditions(lbs, attrib); \/*---- notification message ----*\/ if (info && info[0]) { rsprintf(\"
%s<\/td><\/tr>\\n\", info); } \/*---- page navigation ----*\/ if (!printable) { show_page_filters(lbs, n_msg, page_n, mode_commands, mode); show_page_navigation(lbs, n_msg, page_n, n_page); } \/*---- select navigation ----*\/ if (isparam(\"select\") && atoi(getparam(\"select\")) == 1) show_select_navigation(lbs); \/*---- table titles ----*\/ \/* overall listing table *\/ rsprintf(\"
\\n\"); size = printable ? 2 : 3; show_text = TRUE; text_in_attr = FALSE; list[0] = 0; getcfg(lbs->name, \"List display\", list, 10000); \/* evaluate Guest display list *\/ if (getcfg(lbs->name, \"Password file\", str, sizeof(str)) && getcfg(lbs->name, \"Guest list display\", str, sizeof(str)) && !isparam(\"unm\")) { strcpy(list, str); n = strbreak(list, (char (*)[NAME_LENGTH]) gattr, MAX_N_ATTR, \",\", FALSE); for (j = 0; j < n; j++) if (strieq(gattr + j * NAME_LENGTH, \"text\")) break; if (n > 0 && j == n) show_text = FALSE; else text_in_attr = TRUE; } memset(disp_attr_flags, 0, sizeof(disp_attr_flags)); if (list[0]) { n_attr_disp = strbreak(list, disp_attr, MAX_N_ATTR, \",\", FALSE); \/* if text is in guest display list, adjust number of *real* attributes *\/ if (text_in_attr) n_attr_disp--; if (search_all) { for (i = n_attr_disp - 1; i >= 0; i--) strcpy(disp_attr[i + 1], disp_attr[i]); strcpy(disp_attr[0], loc(\"Logbook\")); n_attr_disp++; } } else { if (search_all) { n_attr_disp = lbs->n_attr + 3; strcpy(disp_attr[0], loc(\"Logbook\")); strcpy(disp_attr[1], loc(\"ID\")); strcpy(disp_attr[2], loc(\"Date\")); memcpy(disp_attr + 3, attr_list, sizeof(attr_list)); memcpy(disp_attr_flags + 3, attr_flags, sizeof(attr_flags)); } else { n_attr_disp = lbs->n_attr + 2; strcpy(disp_attr[0], loc(\"ID\")); strcpy(disp_attr[1], loc(\"Date\")); memcpy(disp_attr + 2, attr_list, sizeof(attr_list)); memcpy(disp_attr_flags + 2, attr_flags, sizeof(attr_flags)); } } list[0] = 0; getcfg(lbs->name, \"Link display\", list, 10000); if (list[0]) { n = strbreak(list, (char (*)[NAME_LENGTH]) gattr, MAX_N_ATTR, \",\", FALSE); for (i = 0; i < n_attr_disp; i++) { for (j = 0; j < n; j++) if (strieq(gattr + j * NAME_LENGTH, disp_attr[i])) break; if (j < n) disp_attr_link[i] = TRUE; else disp_attr_link[i] = FALSE; } } else for (i = 0; i < n_attr_disp; i++) disp_attr_link[i] = TRUE; if (threaded) { } else { rsprintf(\"\\n\"); \/* empty title for selection box *\/ if (isparam(\"select\") && atoi(getparam(\"select\")) == 1) rsprintf(\"
 <\/th>\\n\"); for (i = 0; i < n_attr_disp; i++) { \/* assemble current command line, replace sort statements *\/ strlcpy(ref, getparam(\"cmdline\"), sizeof(ref)); strlcpy(str, disp_attr[i], sizeof(str)); url_encode(str, sizeof(str)); if (isparam(\"sort\") && strcmp(getparam(\"sort\"), disp_attr[i]) == 0) { subst_param(ref, sizeof(ref), \"sort\", \"\"); subst_param(ref, sizeof(ref), \"rsort\", str); } else { if (ref[0] == 0) { if (getcfg(lbs->name, \"Reverse sort\", str2, sizeof(str2)) && atoi(str2) == 1) sprintf(ref, \"?rsort=%s\", str); else sprintf(ref, \"?sort=%s\", str); } else { subst_param(ref, sizeof(ref), \"rsort\", \"\"); subst_param(ref, sizeof(ref), \"sort\", str); } } img[0] = 0; if (isparam(\"sort\") && strcmp(getparam(\"sort\"), disp_attr[i]) == 0) sprintf(img, \"\\\"%s\\\"\", loc(\"up\"), loc(\"up\")); else if (isparam(\"rsort\") && strcmp(getparam(\"rsort\"), disp_attr[i]) == 0) sprintf(img, \"\\\"%s\\\"\", loc(\"down\"), loc(\"down\")); sprintf(str, \"Tooltip %s\", disp_attr[i]); if (getcfg(lbs->name, str, comment, sizeof(comment))) sprintf(str, \"title=\\\"%s\\\"\", comment); else str[0] = 0; if (strieq(disp_attr[i], \"Edit\") || strieq(disp_attr[i], \"Delete\")) rsprintf(\"%s<\/th>\\n\", str, disp_attr[i]); else { rsprintf(\"%s<\/a>%s<\/th>\\n\", disp_attr[i], img); } } if (!strieq(mode, \"Full\") && n_line > 0 && show_text) rsprintf(\"%s<\/th>\\n\", loc(\"Text\")); if (show_att_column) rsprintf(\"\\\"%s\\\"\", loc(\"Attachments\"), loc(\"Attachments\")); rsprintf(\"<\/tr>\\n\\n\"); } } \/* if (!csv && !xml) *\/ \/*---- display message list ----*\/ for (index = i_start; index <= i_stop; index++) { size = TEXT_SIZE; message_id = msg_list[index].lbs->el_index[msg_list[index].index].message_id; status = el_retrieve(msg_list[index].lbs, message_id, date, attr_list, attrib, lbs->n_attr, text, &size, in_reply_to, reply_to, attachment, encoding, locked_by, draft); if (status != EL_SUCCESS) break; \/* skip drafts *\/ if (getcfg(lbs->name, \"List drafts\", str, sizeof(str)) && atoi(str) == 0) if (draft[0]) continue; if (csv) { rsprintf(\"%d\", message_id); if (strieq(mode, \"CSV1\")) rsprintf(\",\"); else rsprintf(\";\"); strlcpy(str, date, sizeof(str)); while (strchr(str, ',')) *strchr(str, ',') = ' '; rsprintf(str); if (strieq(mode, \"CSV1\")) rsprintf(\",\"); else rsprintf(\";\"); for (i = 0; i < lbs->n_attr; i++) { strlcpy(str, attrib[i], sizeof(str)); if (str[0]) { if (attr_flags[i] & AF_DATE) { sprintf(str, \"Date format %s\", attr_list[i]); if (!getcfg(lbs->name, str, format, sizeof(format))) if (!getcfg(lbs->name, \"Date format\", format, sizeof(format))) strcpy(format, DEFAULT_DATE_FORMAT); ltime = atoi(attrib[i]); ptms = localtime(<ime); assert(ptms); if (ltime == 0) strcpy(str, \"-\"); else my_strftime(str, sizeof(str), format, ptms); } else if (attr_flags[i] & AF_DATETIME) { sprintf(str, \"Time format %s\", attr_list[i]); if (!getcfg(lbs->name, str, format, sizeof(format))) if (!getcfg(lbs->name, \"Time format\", format, sizeof(format))) strcpy(format, DEFAULT_TIME_FORMAT); ltime = atoi(attrib[i]); ptms = localtime(<ime); assert(ptms); if (ltime == 0) strcpy(str, \"-\"); else my_strftime(str, sizeof(str), format, ptms); } rsputs(\"\\\"\"); pt1 = str; while ((pt2 = strchr(pt1, '\"')) != NULL) { *pt2 = 0; rsputs(pt1); rsputs(\"\\\"\\\"\"); pt1 = pt2 + 1; } rsputs(pt1); rsputs(\"\\\"\"); } if (i < lbs->n_attr - 1) { if (strieq(mode, \"CSV1\")) rsprintf(\",\"); else rsprintf(\";\"); } else { if (strlen(text) > 0 && strieq(mode, \"CSV3\")) { rsprintf(\";\"); strlcpy(str, text, sizeof(str)); rsputs(\"\\\"\"); pt1 = str; while ((pt2 = strchr(pt1, '\"')) != NULL) { *pt2 = 0; rsputs(pt1); rsputs(\"\\\"\\\"\"); pt1 = pt2 + 1; } rsputs(pt1); rsputs(\"\\\"\"); } rsprintf(\"\\r\\n\"); } } } else if (xml) { rsputs(\"\\t\\n\"); rsprintf(\"\\t\\t%d<\/MID>\\n\", message_id); rsprintf(\"\\t\\t%s<\/DATE>\\n\", date); if (in_reply_to[0]) rsprintf(\"\\t\\t%s<\/IN_REPLY_TO>\\n\", in_reply_to); if (reply_to[0]) rsprintf(\"\\t\\t%s<\/REPLY_TO>\\n\", reply_to); if (attachment[0][0]) { rsprintf(\"\\t\\t\"); rsprintf(attachment[0]); for (i = 1; i < MAX_ATTACHMENTS; i++) if (attachment[i][0]) rsprintf(\",%s\", attachment[i]); rsprintf(\"<\/ATTACHMENT>\\n\", attachment); } rsprintf(\"\\t\\t%s<\/ENCODING>\\n\", encoding); for (i = 0; i < lbs->n_attr; i++) { strcpy(iattr, attr_list[i]); for (j = 0; j < (int) strlen(iattr); j++) \/* replace special characters with \"_\", exclude any UTF-8 *\/ if (!isalnum(iattr[j]) && ((unsigned char) iattr[j] < 128)) iattr[j] = '_'; rsprintf(\"\\t\\t<%s>\", iattr); strlcpy(str, attrib[i], sizeof(str)); if (attr_flags[i] & AF_DATE) { sprintf(str, \"Date format %s\", attr_list[i]); if (!getcfg(lbs->name, str, format, sizeof(format))) if (!getcfg(lbs->name, \"Date format\", format, sizeof(format))) strcpy(format, DEFAULT_DATE_FORMAT); ltime = atoi(attrib[i]); ptms = localtime(<ime); assert(ptms); if (ltime == 0) strcpy(str, \"-\"); else my_strftime(str, sizeof(str), format, ptms); sprintf(str + strlen(str), \" [%ld]\", (long)ltime); } else if (attr_flags[i] & AF_DATETIME) { sprintf(str, \"Time format %s\", attr_list[i]); if (!getcfg(lbs->name, str, format, sizeof(format))) if (!getcfg(lbs->name, \"Time format\", format, sizeof(format))) strcpy(format, DEFAULT_TIME_FORMAT); ltime = atoi(attrib[i]); ptms = localtime(<ime); assert(ptms); if (ltime == 0) strcpy(str, \"-\"); else my_strftime(str, sizeof(str), format, ptms); sprintf(str + strlen(str), \" [%ld]\", (long)ltime); } xmlencode(str); rsprintf(\"<\/%s>\\n\", iattr); } rsputs(\"\\t\\t\"); xmlencode(text); rsputs(\"<\/TEXT>\\n\"); rsputs(\"\\t<\/ENTRY>\\n\"); } else if (raw) { rsprintf(\"$@MID@$: %d\\r\\n\", message_id); rsprintf(\"Date: %s\\r\\n\", date); if (reply_to[0]) rsprintf(\"Reply to: %s\\r\\n\", reply_to); if (in_reply_to[0]) rsprintf(\"In reply to: %s\\r\\n\", in_reply_to); for (i = 0; i < lbs->n_attr; i++) rsprintf(\"%s: %s\\r\\n\", attr_list[i], attrib[i]); rsprintf(\"Attachment: \"); if (attachment[0][0]) { rsprintf(\"%s\", attachment[0]); for (i = 1; i < MAX_ATTACHMENTS; i++) if (attachment[i][0]) rsprintf(\",%s\", attachment[i]); } rsprintf(\"\\r\\n\"); rsprintf(\"Encoding: %s\\r\\n\", encoding); if (locked_by[0]) rsprintf(\"Locked by: %s\\r\\n\", locked_by); rsprintf(\"========================================\\r\\n\"); rsputs(text); rsputs(\"\\r\\n\"); } else { \/*---- add highlighting for searched subtext ----*\/ if (isparam(\"subtext\")) { highlight_searchtext(re_buf, text, text1, strieq(encoding, \"plain\") || strieq(encoding, \"ELCode\") || !strieq(mode, \"Full\")); strlcpy(text, text1, TEXT_SIZE); } \/*---- display line ----*\/ expand = 1; if (threaded) { if (getcfg(lbs->name, \"Expand default\", str, sizeof(str))) expand = atoi(str); if (isparam(\"expand\")) expand = atoi(getparam(\"expand\")); } level = 0; if (!filtering && !date_filtering) { if (expand == 0 && (!getcfg(lbs->name, \"Collapse to last\", str, sizeof(str)) || atoi(str) == 1)) { \/* search last entry in this thread *\/ if (reply_to[0]) { search_last_reply(msg_list[index].lbs, &message_id); size = TEXT_SIZE; status = el_retrieve(msg_list[index].lbs, message_id, date, attr_list, attrib, lbs->n_attr, text, &size, in_reply_to, reply_to, attachment, encoding, locked_by, draft); if (status == SUCCESS) level = 1; } } } else if (in_reply_to[0]) level = 1; display_line(msg_list[index].lbs, message_id, index, mode, expand, level, printable, n_line, show_attachments, show_att_column, date, in_reply_to, reply_to, n_attr_disp, disp_attr, disp_attr_link, attrib, lbs->n_attr, text, show_text, attachment, encoding, isparam(\"select\") ? atoi(getparam(\"select\")) : 0, &n_display, locked_by, 0, re_buf, page_mid, FALSE, draft); if (threaded && !filtering && !date_filtering) { if (reply_to[0] && expand > 0) { p = reply_to; do { display_reply(msg_list[index].lbs, atoi(p), printable, expand, n_line, n_attr_disp, disp_attr, show_text, 1, 0, re_buf, page_mid, FALSE); while (*p && isdigit(*p)) p++; while (*p && (*p == ',' || *p == ' ')) p++; } while (*p); } } } \/* if (!csv && !xml) *\/ } \/* for() *\/ if (!csv && !xml && !raw) { rsprintf(\"<\/table>\\n\"); if (n_display) rsprintf(\"\\n\", n_display); rsprintf(\"<\/td><\/tr>\\n\"); if (n_msg == 0) rsprintf(\"
%s<\/td><\/tr>\", loc(\"No entries found\")); \/*---- page navigation ----*\/ if (!printable) show_page_navigation(lbs, n_msg, page_n, n_page); rsprintf(\"<\/table>\\n\"); show_bottom_text(lbs); rsprintf(\"<\/form><\/body><\/html>\\r\\n\"); } if (xml) { rsputs(\"<\/ELOG_LIST>\\n\"); } regfree(re_buf); for (i = 0; i < lbs->n_attr; i++) regfree(re_buf + 1 + i); xfree(slist); xfree(svalue); xfree(gattr); xfree(list); xfree(msg_list); xfree(text); xfree(text1); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":468399,"input":"receive_msg(BOOL extract_recip) { int i; int rc = FAIL; int msg_size = 0; int process_info_len = Ustrlen(process_info); int error_rc = (error_handling == ERRORS_SENDER)? errors_sender_rc : EXIT_FAILURE; int header_size = 256; int start, end, domain; int id_resolution; int had_zero = 0; int prevlines_length = 0; register int ptr = 0; BOOL contains_resent_headers = FALSE; BOOL extracted_ignored = FALSE; BOOL first_line_ended_crlf = TRUE_UNSET; BOOL smtp_yield = TRUE; BOOL yield = FALSE; BOOL resents_exist = FALSE; uschar *resent_prefix = US\"\"; uschar *blackholed_by = NULL; uschar *blackhole_log_msg = US\"\"; enum {NOT_TRIED, TMP_REJ, PERM_REJ, ACCEPTED} cutthrough_done = NOT_TRIED; flock_t lock_data; error_block *bad_addresses = NULL; uschar *frozen_by = NULL; uschar *queued_by = NULL; uschar *errmsg; gstring * g; struct stat statbuf; \/* Final message to give to SMTP caller, and messages from ACLs *\/ uschar *smtp_reply = NULL; uschar *user_msg, *log_msg; \/* Working header pointers *\/ header_line *h, *next; \/* Flags for noting the existence of certain headers (only one left) *\/ BOOL date_header_exists = FALSE; \/* Pointers to receive the addresses of headers whose contents we need. *\/ header_line *from_header = NULL; header_line *subject_header = NULL; header_line *msgid_header = NULL; header_line *received_header; #ifdef EXPERIMENTAL_DMARC int dmarc_up = 0; #endif \/* EXPERIMENTAL_DMARC *\/ \/* Variables for use when building the Received: header. *\/ uschar *timestamp; int tslen; \/* Release any open files that might have been cached while preparing to accept the message - e.g. by verifying addresses - because reading a message might take a fair bit of real time. *\/ search_tidyup(); \/* Extracting the recipient list from an input file is incompatible with cutthrough delivery with the no-spool option. It shouldn't be possible to set up the combination, but just in case kill any ongoing connection. *\/ if (extract_recip || !smtp_input) cancel_cutthrough_connection(TRUE, US\"not smtp input\"); \/* Initialize the chain of headers by setting up a place-holder for Received: header. Temporarily mark it as \"old\", i.e. not to be used. We keep header_last pointing to the end of the chain to make adding headers simple. *\/ received_header = header_list = header_last = store_get(sizeof(header_line)); header_list->next = NULL; header_list->type = htype_old; header_list->text = NULL; header_list->slen = 0; \/* Control block for the next header to be read. *\/ next = store_get(sizeof(header_line)); next->text = store_get(header_size); \/* Initialize message id to be null (indicating no message read), and the header names list to be the normal list. Indicate there is no data file open yet, initialize the size and warning count, and deal with no size limit. *\/ message_id[0] = 0; data_file = NULL; data_fd = -1; spool_name = US\"\"; message_size = 0; warning_count = 0; received_count = 1; \/* For the one we will add *\/ if (thismessage_size_limit <= 0) thismessage_size_limit = INT_MAX; \/* While reading the message, the following counts are computed. *\/ message_linecount = body_linecount = body_zerocount = max_received_linelength = 0; #ifndef DISABLE_DKIM \/* Call into DKIM to set up the context. In CHUNKING mode we clear the dot-stuffing flag *\/ if (smtp_input && !smtp_batched_input && !dkim_disable_verify) dkim_exim_verify_init(chunking_state <= CHUNKING_OFFERED); #endif #ifdef EXPERIMENTAL_DMARC \/* initialize libopendmarc *\/ dmarc_up = dmarc_init(); #endif \/* Remember the time of reception. Exim uses time+pid for uniqueness of message ids, and fractions of a second are required. See the comments that precede the message id creation below. *\/ (void)gettimeofday(&message_id_tv, NULL); \/* For other uses of the received time we can operate with granularity of one second, and for that we use the global variable received_time. This is for things like ultimate message timeouts.XXX *\/ received_time = message_id_tv; \/* If SMTP input, set the special handler for timeouts. The alarm() calls happen in the smtp_getc() function when it refills its buffer. *\/ if (smtp_input) os_non_restarting_signal(SIGALRM, data_timeout_handler); \/* If not SMTP input, timeout happens only if configured, and we just set a single timeout for the whole message. *\/ else if (receive_timeout > 0) { os_non_restarting_signal(SIGALRM, data_timeout_handler); alarm(receive_timeout); } \/* SIGTERM and SIGINT are caught always. *\/ signal(SIGTERM, data_sigterm_sigint_handler); signal(SIGINT, data_sigterm_sigint_handler); \/* Header lines in messages are not supposed to be very long, though when unfolded, to: and cc: headers can take up a lot of store. We must also cope with the possibility of junk being thrown at us. Start by getting 256 bytes for storing the header, and extend this as necessary using string_cat(). To cope with total lunacies, impose an upper limit on the length of the header section of the message, as otherwise the store will fill up. We must also cope with the possibility of binary zeros in the data. Hence we cannot use fgets(). Folded header lines are joined into one string, leaving the '\\n' characters inside them, so that writing them out reproduces the input. Loop for each character of each header; the next structure for chaining the header is set up already, with ptr the offset of the next character in next->text. *\/ for (;;) { int ch = (receive_getc)(GETC_BUFFER_UNLIMITED); \/* If we hit EOF on a SMTP connection, it's an error, since incoming SMTP must have a correct \".\" terminator. *\/ if (ch == EOF && smtp_input \/* && !smtp_batched_input *\/) { smtp_reply = handle_lost_connection(US\" (header)\"); smtp_yield = FALSE; goto TIDYUP; \/* Skip to end of function *\/ } \/* See if we are at the current header's size limit - there must be at least four bytes left. This allows for the new character plus a zero, plus two for extra insertions when we are playing games with dots and carriage returns. If we are at the limit, extend the text buffer. This could have been done automatically using string_cat() but because this is a tightish loop storing only one character at a time, we choose to do it inline. Normally store_extend() will be able to extend the block; only at the end of a big store block will a copy be needed. To handle the case of very long headers (and sometimes lunatic messages can have ones that are 100s of K long) we call store_release() for strings that have been copied - if the string is at the start of a block (and therefore the only thing in it, because we aren't doing any other gets), the block gets freed. We can only do this release if there were no allocations since the once that we want to free. *\/ if (ptr >= header_size - 4) { int oldsize = header_size; \/* header_size += 256; *\/ header_size *= 2; if (!store_extend(next->text, oldsize, header_size)) { BOOL release_ok = store_last_get[store_pool] == next->text; uschar *newtext = store_get(header_size); memcpy(newtext, next->text, ptr); if (release_ok) store_release(next->text); next->text = newtext; } } \/* Cope with receiving a binary zero. There is dispute about whether these should be allowed in RFC 822 messages. The middle view is that they should not be allowed in headers, at least. Exim takes this attitude at the moment. We can't just stomp on them here, because we don't know that this line is a header yet. Set a flag to cause scanning later. *\/ if (ch == 0) had_zero++; \/* Test for termination. Lines in remote SMTP are terminated by CRLF, while those from data files use just LF. Treat LF in local SMTP input as a terminator too. Treat EOF as a line terminator always. *\/ if (ch == EOF) goto EOL; \/* FUDGE: There are sites out there that don't send CRs before their LFs, and other MTAs accept this. We are therefore forced into this \"liberalisation\" too, so we accept LF as a line terminator whatever the source of the message. However, if the first line of the message ended with a CRLF, we treat a bare LF specially by inserting a white space after it to ensure that the header line is not terminated. *\/ if (ch == '\\n') { if (first_line_ended_crlf == TRUE_UNSET) first_line_ended_crlf = FALSE; else if (first_line_ended_crlf) receive_ungetc(' '); goto EOL; } \/* This is not the end of the line. If this is SMTP input and this is the first character in the line and it is a \".\" character, ignore it. This implements the dot-doubling rule, though header lines starting with dots aren't exactly common. They are legal in RFC 822, though. If the following is CRLF or LF, this is the line that that terminates the entire message. We set message_ended to indicate this has happened (to prevent further reading), and break out of the loop, having freed the empty header, and set next = NULL to indicate no data line. *\/ if (ptr == 0 && ch == '.' && (smtp_input || dot_ends)) { ch = (receive_getc)(GETC_BUFFER_UNLIMITED); if (ch == '\\r') { ch = (receive_getc)(GETC_BUFFER_UNLIMITED); if (ch != '\\n') { receive_ungetc(ch); ch = '\\r'; \/* Revert to CR *\/ } } if (ch == '\\n') { message_ended = END_DOT; store_reset(next); next = NULL; break; \/* End character-reading loop *\/ } \/* For non-SMTP input, the dot at the start of the line was really a data character. What is now in ch is the following character. We guaranteed enough space for this above. *\/ if (!smtp_input) { next->text[ptr++] = '.'; message_size++; } } \/* If CR is immediately followed by LF, end the line, ignoring the CR, and remember this case if this is the first line ending. *\/ if (ch == '\\r') { ch = (receive_getc)(GETC_BUFFER_UNLIMITED); if (ch == '\\n') { if (first_line_ended_crlf == TRUE_UNSET) first_line_ended_crlf = TRUE; goto EOL; } \/* Otherwise, put back the character after CR, and turn the bare CR into LF SP. *\/ ch = (receive_ungetc)(ch); next->text[ptr++] = '\\n'; message_size++; ch = ' '; } \/* We have a data character for the header line. *\/ next->text[ptr++] = ch; \/* Add to buffer *\/ message_size++; \/* Total message size so far *\/ \/* Handle failure due to a humungously long header section. The >= allows for the terminating \\n. Add what we have so far onto the headers list so that it gets reflected in any error message, and back up the just-read character. *\/ if (message_size >= header_maxsize) { next->text[ptr] = 0; next->slen = ptr; next->type = htype_other; next->next = NULL; header_last->next = next; header_last = next; log_write(0, LOG_MAIN, \"ridiculously long message header received from \" \"%s (more than %d characters): message abandoned\", sender_host_unknown? sender_ident : sender_fullhost, header_maxsize); if (smtp_input) { smtp_reply = US\"552 Message header is ridiculously long\"; receive_swallow_smtp(); goto TIDYUP; \/* Skip to end of function *\/ } else { give_local_error(ERRMESS_VLONGHEADER, string_sprintf(\"message header longer than %d characters received: \" \"message not accepted\", header_maxsize), US\"\", error_rc, stdin, header_list->next); \/* Does not return *\/ } } continue; \/* With next input character *\/ \/* End of header line reached *\/ EOL: \/* Keep track of lines for BSMTP errors and overall message_linecount. *\/ receive_linecount++; message_linecount++; \/* Keep track of maximum line length *\/ if (ptr - prevlines_length > max_received_linelength) max_received_linelength = ptr - prevlines_length; prevlines_length = ptr + 1; \/* Now put in the terminating newline. There is always space for at least two more characters. *\/ next->text[ptr++] = '\\n'; message_size++; \/* A blank line signals the end of the headers; release the unwanted space and set next to NULL to indicate this. *\/ if (ptr == 1) { store_reset(next); next = NULL; break; } \/* There is data in the line; see if the next input character is a whitespace character. If it is, we have a continuation of this header line. There is always space for at least one character at this point. *\/ if (ch != EOF) { int nextch = (receive_getc)(GETC_BUFFER_UNLIMITED); if (nextch == ' ' || nextch == '\\t') { next->text[ptr++] = nextch; message_size++; continue; \/* Iterate the loop *\/ } else if (nextch != EOF) (receive_ungetc)(nextch); \/* For next time *\/ else ch = EOF; \/* Cause main loop to exit at end *\/ } \/* We have got to the real line end. Terminate the string and release store beyond it. If it turns out to be a real header, internal binary zeros will be squashed later. *\/ next->text[ptr] = 0; next->slen = ptr; store_reset(next->text + ptr + 1); \/* Check the running total size against the overall message size limit. We don't expect to fail here, but if the overall limit is set less than MESSAGE_ MAXSIZE and a big header is sent, we want to catch it. Just stop reading headers - the code to read the body will then also hit the buffer. *\/ if (message_size > thismessage_size_limit) break; \/* A line that is not syntactically correct for a header also marks the end of the headers. In this case, we leave next containing the first data line. This might actually be several lines because of the continuation logic applied above, but that doesn't matter. It turns out that smail, and presumably sendmail, accept leading lines of the form From ph10 Fri Jan 5 12:35 GMT 1996 in messages. The \"mail\" command on Solaris 2 sends such lines. I cannot find any documentation of this, but for compatibility it had better be accepted. Exim restricts it to the case of non-smtp messages, and treats it as an alternative to the -f command line option. Thus it is ignored except for trusted users or filter testing. Otherwise it is taken as the sender address, unless -f was used (sendmail compatibility). It further turns out that some UUCPs generate the From_line in a different format, e.g. From ph10 Fri, 7 Jan 97 14:00:00 GMT The regex for matching these things is now capable of recognizing both formats (including 2- and 4-digit years in the latter). In fact, the regex is now configurable, as is the expansion string to fish out the sender. Even further on it has been discovered that some broken clients send these lines in SMTP messages. There is now an option to ignore them from specified hosts or networks. Sigh. *\/ if (header_last == header_list && (!smtp_input || (sender_host_address != NULL && verify_check_host(&ignore_fromline_hosts) == OK) || (sender_host_address == NULL && ignore_fromline_local) ) && regex_match_and_setup(regex_From, next->text, 0, -1)) { if (!sender_address_forced) { uschar *uucp_sender = expand_string(uucp_from_sender); if (uucp_sender == NULL) { log_write(0, LOG_MAIN|LOG_PANIC, \"expansion of \\\"%s\\\" failed after matching \" \"\\\"From \\\" line: %s\", uucp_from_sender, expand_string_message); } else { int start, end, domain; uschar *errmess; uschar *newsender = parse_extract_address(uucp_sender, &errmess, &start, &end, &domain, TRUE); if (newsender != NULL) { if (domain == 0 && newsender[0] != 0) newsender = rewrite_address_qualify(newsender, FALSE); if (filter_test != FTEST_NONE || receive_check_set_sender(newsender)) { sender_address = newsender; if (trusted_caller || filter_test != FTEST_NONE) { authenticated_sender = NULL; originator_name = US\"\"; sender_local = FALSE; } if (filter_test != FTEST_NONE) printf(\"Sender taken from \\\"From \\\" line\\n\"); } } } } } \/* Not a leading \"From \" line. Check to see if it is a valid header line. Header names may contain any non-control characters except space and colon, amazingly. *\/ else { uschar *p = next->text; \/* If not a valid header line, break from the header reading loop, leaving next != NULL, indicating that it holds the first line of the body. *\/ if (isspace(*p)) break; while (mac_isgraph(*p) && *p != ':') p++; while (isspace(*p)) p++; if (*p != ':') { body_zerocount = had_zero; break; } \/* We have a valid header line. If there were any binary zeroes in the line, stomp on them here. *\/ if (had_zero > 0) for (p = next->text; p < next->text + ptr; p++) if (*p == 0) *p = '?'; \/* It is perfectly legal to have an empty continuation line at the end of a header, but it is confusing to humans looking at such messages, since it looks like a blank line. Reduce confusion by removing redundant white space at the end. We know that there is at least one printing character (the ':' tested for above) so there is no danger of running off the end. *\/ p = next->text + ptr - 2; for (;;) { while (*p == ' ' || *p == '\\t') p--; if (*p != '\\n') break; ptr = (p--) - next->text + 1; message_size -= next->slen - ptr; next->text[ptr] = 0; next->slen = ptr; } \/* Add the header to the chain *\/ next->type = htype_other; next->next = NULL; header_last->next = next; header_last = next; \/* Check the limit for individual line lengths. This comes after adding to the chain so that the failing line is reflected if a bounce is generated (for a local message). *\/ if (header_line_maxsize > 0 && next->slen > header_line_maxsize) { log_write(0, LOG_MAIN, \"overlong message header line received from \" \"%s (more than %d characters): message abandoned\", sender_host_unknown? sender_ident : sender_fullhost, header_line_maxsize); if (smtp_input) { smtp_reply = US\"552 A message header line is too long\"; receive_swallow_smtp(); goto TIDYUP; \/* Skip to end of function *\/ } else { give_local_error(ERRMESS_VLONGHDRLINE, string_sprintf(\"message header line longer than %d characters \" \"received: message not accepted\", header_line_maxsize), US\"\", error_rc, stdin, header_list->next); \/* Does not return *\/ } } \/* Note if any resent- fields exist. *\/ if (!resents_exist && strncmpic(next->text, US\"resent-\", 7) == 0) { resents_exist = TRUE; resent_prefix = US\"Resent-\"; } } \/* Reject CHUNKING messages that do not CRLF their first header line *\/ if (!first_line_ended_crlf && chunking_state > CHUNKING_OFFERED) { log_write(L_size_reject, LOG_MAIN|LOG_REJECT, \"rejected from <%s>%s%s%s%s: \" \"Non-CRLF-terminated header, under CHUNKING: message abandoned\", sender_address, sender_fullhost ? \" H=\" : \"\", sender_fullhost ? sender_fullhost : US\"\", sender_ident ? \" U=\" : \"\", sender_ident ? sender_ident : US\"\"); smtp_printf(\"552 Message header not CRLF terminated\\r\\n\", FALSE); bdat_flush_data(); smtp_reply = US\"\"; goto TIDYUP; \/* Skip to end of function *\/ } \/* The line has been handled. If we have hit EOF, break out of the loop, indicating no pending data line. *\/ if (ch == EOF) { next = NULL; break; } \/* Set up for the next header *\/ header_size = 256; next = store_get(sizeof(header_line)); next->text = store_get(header_size); ptr = 0; had_zero = 0; prevlines_length = 0; } \/* Continue, starting to read the next header *\/ \/* At this point, we have read all the headers into a data structure in main store. The first header is still the dummy placeholder for the Received: header we are going to generate a bit later on. If next != NULL, it contains the first data line - which terminated the headers before reaching a blank line (not the normal case). *\/ DEBUG(D_receive) { debug_printf(\">>Headers received:\\n\"); for (h = header_list->next; h; h = h->next) debug_printf(\"%s\", h->text); debug_printf(\"\\n\"); } \/* End of file on any SMTP connection is an error. If an incoming SMTP call is dropped immediately after valid headers, the next thing we will see is EOF. We must test for this specially, as further down the reading of the data is skipped if already at EOF. *\/ if (smtp_input && (receive_feof)()) { smtp_reply = handle_lost_connection(US\" (after header)\"); smtp_yield = FALSE; goto TIDYUP; \/* Skip to end of function *\/ } \/* If this is a filter test run and no headers were read, output a warning in case there is a mistake in the test message. *\/ if (filter_test != FTEST_NONE && header_list->next == NULL) printf(\"Warning: no message headers read\\n\"); \/* Scan the headers to identify them. Some are merely marked for later processing; some are dealt with here. *\/ for (h = header_list->next; h; h = h->next) { BOOL is_resent = strncmpic(h->text, US\"resent-\", 7) == 0; if (is_resent) contains_resent_headers = TRUE; switch (header_checkname(h, is_resent)) { case htype_bcc: h->type = htype_bcc; \/* Both Bcc: and Resent-Bcc: *\/ break; case htype_cc: h->type = htype_cc; \/* Both Cc: and Resent-Cc: *\/ break; \/* Record whether a Date: or Resent-Date: header exists, as appropriate. *\/ case htype_date: if (!resents_exist || is_resent) date_header_exists = TRUE; break; \/* Same comments as about Return-Path: below. *\/ case htype_delivery_date: if (delivery_date_remove) h->type = htype_old; break; \/* Same comments as about Return-Path: below. *\/ case htype_envelope_to: if (envelope_to_remove) h->type = htype_old; break; \/* Mark all \"From:\" headers so they get rewritten. Save the one that is to be used for Sender: checking. For Sendmail compatibility, if the \"From:\" header consists of just the login id of the user who called Exim, rewrite it with the gecos field first. Apply this rule to Resent-From: if there are resent- fields. *\/ case htype_from: h->type = htype_from; if (!resents_exist || is_resent) { from_header = h; if (!smtp_input) { int len; uschar *s = Ustrchr(h->text, ':') + 1; while (isspace(*s)) s++; len = h->slen - (s - h->text) - 1; if (Ustrlen(originator_login) == len && strncmpic(s, originator_login, len) == 0) { uschar *name = is_resent? US\"Resent-From\" : US\"From\"; header_add(htype_from, \"%s: %s <%s@%s>\\n\", name, originator_name, originator_login, qualify_domain_sender); from_header = header_last; h->type = htype_old; DEBUG(D_receive|D_rewrite) debug_printf(\"rewrote \\\"%s:\\\" header using gecos\\n\", name); } } } break; \/* Identify the Message-id: header for generating \"in-reply-to\" in the autoreply transport. For incoming logging, save any resent- value. In both cases, take just the first of any multiples. *\/ case htype_id: if (msgid_header == NULL && (!resents_exist || is_resent)) { msgid_header = h; h->type = htype_id; } break; \/* Flag all Received: headers *\/ case htype_received: h->type = htype_received; received_count++; break; \/* \"Reply-to:\" is just noted (there is no resent-reply-to field) *\/ case htype_reply_to: h->type = htype_reply_to; break; \/* The Return-path: header is supposed to be added to messages when they leave the SMTP system. We shouldn't receive messages that already contain Return-path. However, since Exim generates Return-path: on local delivery, resent messages may well contain it. We therefore provide an option (which defaults on) to remove any Return-path: headers on input. Removal actually means flagging as \"old\", which prevents the header being transmitted with the message. *\/ case htype_return_path: if (return_path_remove) h->type = htype_old; \/* If we are testing a mail filter file, use the value of the Return-Path: header to set up the return_path variable, which is not otherwise set. However, remove any <> that surround the address because the variable doesn't have these. *\/ if (filter_test != FTEST_NONE) { uschar *start = h->text + 12; uschar *end = start + Ustrlen(start); while (isspace(*start)) start++; while (end > start && isspace(end[-1])) end--; if (*start == '<' && end[-1] == '>') { start++; end--; } return_path = string_copyn(start, end - start); printf(\"Return-path taken from \\\"Return-path:\\\" header line\\n\"); } break; \/* If there is a \"Sender:\" header and the message is locally originated, and from an untrusted caller and suppress_local_fixups is not set, or if we are in submission mode for a remote message, mark it \"old\" so that it will not be transmitted with the message, unless active_local_sender_retain is set. (This can only be true if active_local_from_check is false.) If there are any resent- headers in the message, apply this rule to Resent-Sender: instead of Sender:. Messages with multiple resent- header sets cannot be tidily handled. (For this reason, at least one MUA - Pine - turns old resent- headers into X-resent- headers when resending, leaving just one set.) *\/ case htype_sender: h->type = ((!active_local_sender_retain && ( (sender_local && !trusted_caller && !suppress_local_fixups) || submission_mode ) ) && (!resents_exist||is_resent))? htype_old : htype_sender; break; \/* Remember the Subject: header for logging. There is no Resent-Subject *\/ case htype_subject: subject_header = h; break; \/* \"To:\" gets flagged, and the existence of a recipient header is noted, whether it's resent- or not. *\/ case htype_to: h->type = htype_to; \/**** to_or_cc_header_exists = TRUE; ****\/ break; } } \/* Extract recipients from the headers if that is required (the -t option). Note that this is documented as being done *before* any address rewriting takes place. There are two possibilities: (1) According to sendmail documentation for Solaris, IRIX, and HP-UX, any recipients already listed are to be REMOVED from the message. Smail 3 works like this. We need to build a non-recipients tree for that list, because in subsequent processing this data is held in a tree and that's what the spool_write_header() function expects. Make sure that non-recipient addresses are fully qualified and rewritten if necessary. (2) According to other sendmail documentation, -t ADDS extracted recipients to those in the command line arguments (and it is rumoured some other MTAs do this). Therefore, there is an option to make Exim behave this way. *** Notes on \"Resent-\" header lines *** The presence of resent-headers in the message makes -t horribly ambiguous. Experiments with sendmail showed that it uses recipients for all resent- headers, totally ignoring the concept of \"sets of resent- headers\" as described in RFC 2822 section 3.6.6. Sendmail also amalgamates them into a single set with all the addresses in one instance of each header. This seems to me not to be at all sensible. Before release 4.20, Exim 4 gave an error for -t if there were resent- headers in the message. However, after a discussion on the mailing list, I've learned that there are MUAs that use resent- headers with -t, and also that the stuff about sets of resent- headers and their ordering in RFC 2822 is generally ignored. An MUA that submits a message with -t and resent- header lines makes sure that only *its* resent- headers are present; previous ones are often renamed as X-resent- for example. Consequently, Exim has been changed so that, if any resent- header lines are present, the recipients are taken from all of the appropriate resent- lines, and not from the ordinary To:, Cc:, etc. *\/ if (extract_recip) { int rcount = 0; error_block **bnext = &bad_addresses; if (extract_addresses_remove_arguments) { while (recipients_count-- > 0) { uschar *s = rewrite_address(recipients_list[recipients_count].address, TRUE, TRUE, global_rewrite_rules, rewrite_existflags); tree_add_nonrecipient(s); } recipients_list = NULL; recipients_count = recipients_list_max = 0; } \/* Now scan the headers *\/ for (h = header_list->next; h; h = h->next) { if ((h->type == htype_to || h->type == htype_cc || h->type == htype_bcc) && (!contains_resent_headers || strncmpic(h->text, US\"resent-\", 7) == 0)) { uschar *s = Ustrchr(h->text, ':') + 1; while (isspace(*s)) s++; parse_allow_group = TRUE; \/* Allow address group syntax *\/ while (*s != 0) { uschar *ss = parse_find_address_end(s, FALSE); uschar *recipient, *errmess, *p, *pp; int start, end, domain; \/* Check on maximum *\/ if (recipients_max > 0 && ++rcount > recipients_max) { give_local_error(ERRMESS_TOOMANYRECIP, US\"too many recipients\", US\"message rejected: \", error_rc, stdin, NULL); \/* Does not return *\/ } \/* Make a copy of the address, and remove any internal newlines. These may be present as a result of continuations of the header line. The white space that follows the newline must not be removed - it is part of the header. *\/ pp = recipient = store_get(ss - s + 1); for (p = s; p < ss; p++) if (*p != '\\n') *pp++ = *p; *pp = 0; #ifdef SUPPORT_I18N { BOOL b = allow_utf8_domains; allow_utf8_domains = TRUE; #endif recipient = parse_extract_address(recipient, &errmess, &start, &end, &domain, FALSE); #ifdef SUPPORT_I18N if (string_is_utf8(recipient)) message_smtputf8 = TRUE; else allow_utf8_domains = b; } #endif \/* Keep a list of all the bad addresses so we can send a single error message at the end. However, an empty address is not an error; just ignore it. This can come from an empty group list like To: Recipients of list:; If there are no recipients at all, an error will occur later. *\/ if (recipient == NULL && Ustrcmp(errmess, \"empty address\") != 0) { int len = Ustrlen(s); error_block *b = store_get(sizeof(error_block)); while (len > 0 && isspace(s[len-1])) len--; b->next = NULL; b->text1 = string_printing(string_copyn(s, len)); b->text2 = errmess; *bnext = b; bnext = &(b->next); } \/* If the recipient is already in the nonrecipients tree, it must have appeared on the command line with the option extract_addresses_ remove_arguments set. Do not add it to the recipients, and keep a note that this has happened, in order to give a better error if there are no recipients left. *\/ else if (recipient != NULL) { if (tree_search(tree_nonrecipients, recipient) == NULL) receive_add_recipient(recipient, -1); else extracted_ignored = TRUE; } \/* Move on past this address *\/ s = ss + (*ss? 1:0); while (isspace(*s)) s++; } \/* Next address *\/ parse_allow_group = FALSE; \/* Reset group syntax flags *\/ parse_found_group = FALSE; \/* If this was the bcc: header, mark it \"old\", which means it will be kept on the spool, but not transmitted as part of the message. *\/ if (h->type == htype_bcc) h->type = htype_old; } \/* For appropriate header line *\/ } \/* For each header line *\/ } \/* Now build the unique message id. This has changed several times over the lifetime of Exim. This description was rewritten for Exim 4.14 (February 2003). Retaining all the history in the comment has become too unwieldy - read previous release sources if you want it. The message ID has 3 parts: tttttt-pppppp-ss. Each part is a number in base 62. The first part is the current time, in seconds. The second part is the current pid. Both are large enough to hold 32-bit numbers in base 62. The third part can hold a number in the range 0-3843. It used to be a computed sequence number, but is now the fractional component of the current time in units of 1\/2000 of a second (i.e. a value in the range 0-1999). After a message has been received, Exim ensures that the timer has ticked at the appropriate level before proceeding, to avoid duplication if the pid happened to be re-used within the same time period. It seems likely that most messages will take at least half a millisecond to be received, so no delay will normally be necessary. At least for some time... There is a modification when localhost_number is set. Formerly this was allowed to be as large as 255. Now it is restricted to the range 0-16, and the final component of the message id becomes (localhost_number * 200) + fractional time in units of 1\/200 of a second (i.e. a value in the range 0-3399). Some not-really-Unix operating systems use case-insensitive file names (Darwin, Cygwin). For these, we have to use base 36 instead of base 62. Luckily, this still allows the tttttt field to hold a large enough number to last for some more decades, and the final two-digit field can hold numbers up to 1295, which is enough for milliseconds (instead of 1\/2000 of a second). However, the pppppp field cannot hold a 32-bit pid, but it can hold a 31-bit pid, so it is probably safe because pids have to be positive. The localhost_number is restricted to 0-10 for these hosts, and when it is set, the final field becomes (localhost_number * 100) + fractional time in centiseconds. Note that string_base62() returns its data in a static storage block, so it must be copied before calling string_base62() again. It always returns exactly 6 characters. There doesn't seem to be anything in the RFC which requires a message id to start with a letter, but Smail was changed to ensure this. The external form of the message id (as supplied by string expansion) therefore starts with an additional leading 'E'. The spool file names do not include this leading letter and it is not used internally. NOTE: If ever the format of message ids is changed, the regular expression for checking that a string is in this format must be updated in a corresponding way. It appears in the initializing code in exim.c. The macro MESSAGE_ID_LENGTH must also be changed to reflect the correct string length. The queue-sort code needs to know the layout. Then, of course, other programs that rely on the message id format will need updating too. *\/ Ustrncpy(message_id, string_base62((long int)(message_id_tv.tv_sec)), 6); message_id[6] = '-'; Ustrncpy(message_id + 7, string_base62((long int)getpid()), 6); \/* Deal with the case where the host number is set. The value of the number was checked when it was read, to ensure it isn't too big. The timing granularity is left in id_resolution so that an appropriate wait can be done after receiving the message, if necessary (we hope it won't be). *\/ if (host_number_string != NULL) { id_resolution = (BASE_62 == 62)? 5000 : 10000; sprintf(CS(message_id + MESSAGE_ID_LENGTH - 3), \"-%2s\", string_base62((long int)( host_number * (1000000\/id_resolution) + message_id_tv.tv_usec\/id_resolution)) + 4); } \/* Host number not set: final field is just the fractional time at an appropriate resolution. *\/ else { id_resolution = (BASE_62 == 62)? 500 : 1000; sprintf(CS(message_id + MESSAGE_ID_LENGTH - 3), \"-%2s\", string_base62((long int)(message_id_tv.tv_usec\/id_resolution)) + 4); } \/* Add the current message id onto the current process info string if it will fit. *\/ (void)string_format(process_info + process_info_len, PROCESS_INFO_SIZE - process_info_len, \" id=%s\", message_id); \/* If we are using multiple input directories, set up the one for this message to be the least significant base-62 digit of the time of arrival. Otherwise ensure that it is an empty string. *\/ message_subdir[0] = split_spool_directory ? message_id[5] : 0; \/* Now that we have the message-id, if there is no message-id: header, generate one, but only for local (without suppress_local_fixups) or submission mode messages. This can be user-configured if required, but we had better flatten any illegal characters therein. *\/ if (msgid_header == NULL && ((sender_host_address == NULL && !suppress_local_fixups) || submission_mode)) { uschar *p; uschar *id_text = US\"\"; uschar *id_domain = primary_hostname; \/* Permit only letters, digits, dots, and hyphens in the domain *\/ if (message_id_domain != NULL) { uschar *new_id_domain = expand_string(message_id_domain); if (new_id_domain == NULL) { if (!expand_string_forcedfail) log_write(0, LOG_MAIN|LOG_PANIC, \"expansion of \\\"%s\\\" (message_id_header_domain) \" \"failed: %s\", message_id_domain, expand_string_message); } else if (*new_id_domain != 0) { id_domain = new_id_domain; for (p = id_domain; *p != 0; p++) if (!isalnum(*p) && *p != '.') *p = '-'; \/* No need to test '-' ! *\/ } } \/* Permit all characters except controls and RFC 2822 specials in the additional text part. *\/ if (message_id_text != NULL) { uschar *new_id_text = expand_string(message_id_text); if (new_id_text == NULL) { if (!expand_string_forcedfail) log_write(0, LOG_MAIN|LOG_PANIC, \"expansion of \\\"%s\\\" (message_id_header_text) \" \"failed: %s\", message_id_text, expand_string_message); } else if (*new_id_text != 0) { id_text = new_id_text; for (p = id_text; *p != 0; p++) if (mac_iscntrl_or_special(*p)) *p = '-'; } } \/* Add the header line * Resent-* headers are prepended, per RFC 5322 3.6.6. Non-Resent-* are * appended, to preserve classical expectations of header ordering. *\/ header_add_at_position(!resents_exist, NULL, FALSE, htype_id, \"%sMessage-Id: <%s%s%s@%s>\\n\", resent_prefix, message_id_external, (*id_text == 0)? \"\" : \".\", id_text, id_domain); } \/* If we are to log recipients, keep a copy of the raw ones before any possible rewriting. Must copy the count, because later ACLs and the local_scan() function may mess with the real recipients. *\/ if (LOGGING(received_recipients)) { raw_recipients = store_get(recipients_count * sizeof(uschar *)); for (i = 0; i < recipients_count; i++) raw_recipients[i] = string_copy(recipients_list[i].address); raw_recipients_count = recipients_count; } \/* Ensure the recipients list is fully qualified and rewritten. Unqualified recipients will get here only if the conditions were right (allow_unqualified_ recipient is TRUE). *\/ for (i = 0; i < recipients_count; i++) recipients_list[i].address = rewrite_address(recipients_list[i].address, TRUE, TRUE, global_rewrite_rules, rewrite_existflags); \/* If there is no From: header, generate one for local (without suppress_local_fixups) or submission_mode messages. If there is no sender address, but the sender is local or this is a local delivery error, use the originator login. This shouldn't happen for genuine bounces, but might happen for autoreplies. The addition of From: must be done *before* checking for the possible addition of a Sender: header, because untrusted_set_sender allows an untrusted user to set anything in the envelope (which might then get info From:) but we still want to ensure a valid Sender: if it is required. *\/ if (from_header == NULL && ((sender_host_address == NULL && !suppress_local_fixups) || submission_mode)) { uschar *oname = US\"\"; \/* Use the originator_name if this is a locally submitted message and the caller is not trusted. For trusted callers, use it only if -F was used to force its value or if we have a non-SMTP message for which -f was not used to set the sender. *\/ if (sender_host_address == NULL) { if (!trusted_caller || sender_name_forced || (!smtp_input && !sender_address_forced)) oname = originator_name; } \/* For non-locally submitted messages, the only time we use the originator name is when it was forced by the \/name= option on control=submission. *\/ else { if (submission_name != NULL) oname = submission_name; } \/* Envelope sender is empty *\/ if (sender_address[0] == 0) { uschar *fromstart, *fromend; fromstart = string_sprintf(\"%sFrom: %s%s\", resent_prefix, oname, (oname[0] == 0)? \"\" : \" <\"); fromend = (oname[0] == 0)? US\"\" : US\">\"; if (sender_local || local_error_message) { header_add(htype_from, \"%s%s@%s%s\\n\", fromstart, local_part_quote(originator_login), qualify_domain_sender, fromend); } else if (submission_mode && authenticated_id != NULL) { if (submission_domain == NULL) { header_add(htype_from, \"%s%s@%s%s\\n\", fromstart, local_part_quote(authenticated_id), qualify_domain_sender, fromend); } else if (submission_domain[0] == 0) \/* empty => whole address set *\/ { header_add(htype_from, \"%s%s%s\\n\", fromstart, authenticated_id, fromend); } else { header_add(htype_from, \"%s%s@%s%s\\n\", fromstart, local_part_quote(authenticated_id), submission_domain, fromend); } from_header = header_last; \/* To get it checked for Sender: *\/ } } \/* There is a non-null envelope sender. Build the header using the original sender address, before any rewriting that might have been done while verifying it. *\/ else { header_add(htype_from, \"%sFrom: %s%s%s%s\\n\", resent_prefix, oname, (oname[0] == 0)? \"\" : \" <\", (sender_address_unrewritten == NULL)? sender_address : sender_address_unrewritten, (oname[0] == 0)? \"\" : \">\"); from_header = header_last; \/* To get it checked for Sender: *\/ } } \/* If the sender is local (without suppress_local_fixups), or if we are in submission mode and there is an authenticated_id, check that an existing From: is correct, and if not, generate a Sender: header, unless disabled. Any previously-existing Sender: header was removed above. Note that sender_local, as well as being TRUE if the caller of exim is not trusted, is also true if a trusted caller did not supply a -f argument for non-smtp input. To allow trusted callers to forge From: without supplying -f, we have to test explicitly here. If the From: header contains more than one address, then the call to parse_extract_address fails, and a Sender: header is inserted, as required. *\/ if (from_header != NULL && (active_local_from_check && ((sender_local && !trusted_caller && !suppress_local_fixups) || (submission_mode && authenticated_id != NULL)) )) { BOOL make_sender = TRUE; int start, end, domain; uschar *errmess; uschar *from_address = parse_extract_address(Ustrchr(from_header->text, ':') + 1, &errmess, &start, &end, &domain, FALSE); uschar *generated_sender_address; if (submission_mode) { if (submission_domain == NULL) { generated_sender_address = string_sprintf(\"%s@%s\", local_part_quote(authenticated_id), qualify_domain_sender); } else if (submission_domain[0] == 0) \/* empty => full address *\/ { generated_sender_address = string_sprintf(\"%s\", authenticated_id); } else { generated_sender_address = string_sprintf(\"%s@%s\", local_part_quote(authenticated_id), submission_domain); } } else generated_sender_address = string_sprintf(\"%s@%s\", local_part_quote(originator_login), qualify_domain_sender); \/* Remove permitted prefixes and suffixes from the local part of the From: address before doing the comparison with the generated sender. *\/ if (from_address != NULL) { int slen; uschar *at = (domain == 0)? NULL : from_address + domain - 1; if (at != NULL) *at = 0; from_address += route_check_prefix(from_address, local_from_prefix); slen = route_check_suffix(from_address, local_from_suffix); if (slen > 0) { memmove(from_address+slen, from_address, Ustrlen(from_address)-slen); from_address += slen; } if (at != NULL) *at = '@'; if (strcmpic(generated_sender_address, from_address) == 0 || (domain == 0 && strcmpic(from_address, originator_login) == 0)) make_sender = FALSE; } \/* We have to cause the Sender header to be rewritten if there are appropriate rewriting rules. *\/ if (make_sender) { if (submission_mode && submission_name == NULL) header_add(htype_sender, \"%sSender: %s\\n\", resent_prefix, generated_sender_address); else header_add(htype_sender, \"%sSender: %s <%s>\\n\", resent_prefix, submission_mode? submission_name : originator_name, generated_sender_address); } \/* Ensure that a non-null envelope sender address corresponds to the submission mode sender address. *\/ if (submission_mode && sender_address[0] != 0) { if (sender_address_unrewritten == NULL) sender_address_unrewritten = sender_address; sender_address = generated_sender_address; if (Ustrcmp(sender_address_unrewritten, generated_sender_address) != 0) log_write(L_address_rewrite, LOG_MAIN, \"\\\"%s\\\" from env-from rewritten as \\\"%s\\\" by submission mode\", sender_address_unrewritten, generated_sender_address); } } \/* If there are any rewriting rules, apply them to the sender address, unless it has already been rewritten as part of verification for SMTP input. *\/ if (global_rewrite_rules != NULL && sender_address_unrewritten == NULL && sender_address[0] != 0) { sender_address = rewrite_address(sender_address, FALSE, TRUE, global_rewrite_rules, rewrite_existflags); DEBUG(D_receive|D_rewrite) debug_printf(\"rewritten sender = %s\\n\", sender_address); } \/* The headers must be run through rewrite_header(), because it ensures that addresses are fully qualified, as well as applying any rewriting rules that may exist. Qualification of header addresses in a message from a remote host happens only if the host is in sender_unqualified_hosts or recipient_unqualified hosts, as appropriate. For local messages, qualification always happens, unless -bnq is used to explicitly suppress it. No rewriting is done for an unqualified address that is left untouched. We start at the second header, skipping our own Received:. This rewriting is documented as happening *after* recipient addresses are taken from the headers by the -t command line option. An added Sender: gets rewritten here. *\/ for (h = header_list->next; h; h = h->next) { header_line *newh = rewrite_header(h, NULL, NULL, global_rewrite_rules, rewrite_existflags, TRUE); if (newh) h = newh; } \/* An RFC 822 (sic) message is not legal unless it has at least one of \"to\", \"cc\", or \"bcc\". Note that although the minimal examples in RFC 822 show just \"to\" or \"bcc\", the full syntax spec allows \"cc\" as well. If any resent- header exists, this applies to the set of resent- headers rather than the normal set. The requirement for a recipient header has been removed in RFC 2822. At this point in the code, earlier versions of Exim added a To: header for locally submitted messages, and an empty Bcc: header for others. In the light of the changes in RFC 2822, this was dropped in November 2003. *\/ \/* If there is no date header, generate one if the message originates locally (i.e. not over TCP\/IP) and suppress_local_fixups is not set, or if the submission mode flag is set. Messages without Date: are not valid, but it seems to be more confusing if Exim adds one to all remotely-originated messages. As per Message-Id, we prepend if resending, else append. *\/ if (!date_header_exists && ((sender_host_address == NULL && !suppress_local_fixups) || submission_mode)) header_add_at_position(!resents_exist, NULL, FALSE, htype_other, \"%sDate: %s\\n\", resent_prefix, tod_stamp(tod_full)); search_tidyup(); \/* Free any cached resources *\/ \/* Show the complete set of headers if debugging. Note that the first one (the new Received:) has not yet been set. *\/ DEBUG(D_receive) { debug_printf(\">>Headers after rewriting and local additions:\\n\"); for (h = header_list->next; h != NULL; h = h->next) debug_printf(\"%c %s\", h->type, h->text); debug_printf(\"\\n\"); } \/* The headers are now complete in store. If we are running in filter testing mode, that is all this function does. Return TRUE if the message ended with a dot. *\/ if (filter_test != FTEST_NONE) { process_info[process_info_len] = 0; return message_ended == END_DOT; } \/*XXX CHUNKING: need to cancel cutthrough under BDAT, for now. In future, think more if it could be handled. Cannot do onward CHUNKING unless inbound is, but inbound chunking ought to be ok with outbound plain. Could we do onward CHUNKING given inbound CHUNKING? *\/ if (chunking_state > CHUNKING_OFFERED) cancel_cutthrough_connection(FALSE, US\"chunking active\"); \/* Cutthrough delivery: We have to create the Received header now rather than at the end of reception, so the timestamp behaviour is a change to the normal case. Having created it, send the headers to the destination. *\/ if (cutthrough.fd >= 0 && cutthrough.delivery) { if (received_count > received_headers_max) { cancel_cutthrough_connection(TRUE, US\"too many headers\"); if (smtp_input) receive_swallow_smtp(); \/* Swallow incoming SMTP *\/ log_write(0, LOG_MAIN|LOG_REJECT, \"rejected from <%s>%s%s%s%s: \" \"Too many \\\"Received\\\" headers\", sender_address, sender_fullhost ? \"H=\" : \"\", sender_fullhost ? sender_fullhost : US\"\", sender_ident ? \"U=\" : \"\", sender_ident ? sender_ident : US\"\"); message_id[0] = 0; \/* Indicate no message accepted *\/ smtp_reply = US\"550 Too many \\\"Received\\\" headers - suspected mail loop\"; goto TIDYUP; \/* Skip to end of function *\/ } received_header_gen(); add_acl_headers(ACL_WHERE_RCPT, US\"MAIL or RCPT\"); (void) cutthrough_headers_send(); } \/* Open a new spool file for the data portion of the message. We need to access it both via a file descriptor and a stream. Try to make the directory if it isn't there. *\/ spool_name = spool_fname(US\"input\", message_subdir, message_id, US\"-D\"); DEBUG(D_receive) debug_printf(\"Data file name: %s\\n\", spool_name); if ((data_fd = Uopen(spool_name, O_RDWR|O_CREAT|O_EXCL, SPOOL_MODE)) < 0) { if (errno == ENOENT) { (void) directory_make(spool_directory, spool_sname(US\"input\", message_subdir), INPUT_DIRECTORY_MODE, TRUE); data_fd = Uopen(spool_name, O_RDWR|O_CREAT|O_EXCL, SPOOL_MODE); } if (data_fd < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Failed to create spool file %s: %s\", spool_name, strerror(errno)); } \/* Make sure the file's group is the Exim gid, and double-check the mode because the group setting doesn't always get set automatically. *\/ if (fchown(data_fd, exim_uid, exim_gid)) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Failed setting ownership on spool file %s: %s\", spool_name, strerror(errno)); (void)fchmod(data_fd, SPOOL_MODE); \/* We now have data file open. Build a stream for it and lock it. We lock only the first line of the file (containing the message ID) because otherwise there are problems when Exim is run under Cygwin (I'm told). See comments in spool_in.c, where the same locking is done. *\/ data_file = fdopen(data_fd, \"w+\"); lock_data.l_type = F_WRLCK; lock_data.l_whence = SEEK_SET; lock_data.l_start = 0; lock_data.l_len = SPOOL_DATA_START_OFFSET; if (fcntl(data_fd, F_SETLK, &lock_data) < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"Cannot lock %s (%d): %s\", spool_name, errno, strerror(errno)); \/* We have an open, locked data file. Write the message id to it to make it self-identifying. Then read the remainder of the input of this message and write it to the data file. If the variable next != NULL, it contains the first data line (which was read as a header but then turned out not to have the right format); write it (remembering that it might contain binary zeros). The result of fwrite() isn't inspected; instead we call ferror() below. *\/ fprintf(data_file, \"%s-D\\n\", message_id); if (next != NULL) { uschar *s = next->text; int len = next->slen; len = fwrite(s, 1, len, data_file); len = len; \/* compiler quietening *\/ body_linecount++; \/* Assumes only 1 line *\/ } \/* Note that we might already be at end of file, or the logical end of file (indicated by '.'), or might have encountered an error while writing the message id or \"next\" line. *\/ if (!ferror(data_file) && !(receive_feof)() && message_ended != END_DOT) { if (smtp_input) { message_ended = chunking_state <= CHUNKING_OFFERED ? read_message_data_smtp(data_file) : spool_wireformat ? read_message_bdat_smtp_wire(data_file) : read_message_bdat_smtp(data_file); receive_linecount++; \/* The terminating \".\" line *\/ } else message_ended = read_message_data(data_file); receive_linecount += body_linecount; \/* For BSMTP errors mainly *\/ message_linecount += body_linecount; switch (message_ended) { \/* Handle premature termination of SMTP *\/ case END_EOF: if (smtp_input) { Uunlink(spool_name); \/* Lose data file when closed *\/ cancel_cutthrough_connection(TRUE, US\"sender closed connection\"); message_id[0] = 0; \/* Indicate no message accepted *\/ smtp_reply = handle_lost_connection(US\"\"); smtp_yield = FALSE; goto TIDYUP; \/* Skip to end of function *\/ } break; \/* Handle message that is too big. Don't use host_or_ident() in the log message; we want to see the ident value even for non-remote messages. *\/ case END_SIZE: Uunlink(spool_name); \/* Lose the data file when closed *\/ cancel_cutthrough_connection(TRUE, US\"mail too big\"); if (smtp_input) receive_swallow_smtp(); \/* Swallow incoming SMTP *\/ log_write(L_size_reject, LOG_MAIN|LOG_REJECT, \"rejected from <%s>%s%s%s%s: \" \"message too big: read=%d max=%d\", sender_address, (sender_fullhost == NULL)? \"\" : \" H=\", (sender_fullhost == NULL)? US\"\" : sender_fullhost, (sender_ident == NULL)? \"\" : \" U=\", (sender_ident == NULL)? US\"\" : sender_ident, message_size, thismessage_size_limit); if (smtp_input) { smtp_reply = US\"552 Message size exceeds maximum permitted\"; message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_TOOBIG, string_sprintf(\"message too big (max=%d)\", thismessage_size_limit), US\"message rejected: \", error_rc, data_file, header_list); \/* Does not return *\/ } break; \/* Handle bad BDAT protocol sequence *\/ case END_PROTOCOL: Uunlink(spool_name); \/* Lose the data file when closed *\/ cancel_cutthrough_connection(TRUE, US\"sender protocol error\"); smtp_reply = US\"\"; \/* Response already sent *\/ message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } } \/* Restore the standard SIGALRM handler for any subsequent processing. (For example, there may be some expansion in an ACL that uses a timer.) *\/ os_non_restarting_signal(SIGALRM, sigalrm_handler); \/* The message body has now been read into the data file. Call fflush() to empty the buffers in C, and then call fsync() to get the data written out onto the disk, as fflush() doesn't do this (or at least, it isn't documented as having to do this). If there was an I\/O error on either input or output, attempt to send an error message, and unlink the spool file. For non-SMTP input we can then give up. Note that for SMTP input we must swallow the remainder of the input in cases of output errors, since the far end doesn't expect to see anything until the terminating dot line is sent. *\/ if (fflush(data_file) == EOF || ferror(data_file) || EXIMfsync(fileno(data_file)) < 0 || (receive_ferror)()) { uschar *msg_errno = US strerror(errno); BOOL input_error = (receive_ferror)() != 0; uschar *msg = string_sprintf(\"%s error (%s) while receiving message from %s\", input_error? \"Input read\" : \"Spool write\", msg_errno, (sender_fullhost != NULL)? sender_fullhost : sender_ident); log_write(0, LOG_MAIN, \"Message abandoned: %s\", msg); Uunlink(spool_name); \/* Lose the data file *\/ cancel_cutthrough_connection(TRUE, US\"error writing spoolfile\"); if (smtp_input) { if (input_error) smtp_reply = US\"451 Error while reading input data\"; else { smtp_reply = US\"451 Error while writing spool file\"; receive_swallow_smtp(); } message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_IOERR, msg, US\"\", error_rc, data_file, header_list); \/* Does not return *\/ } } \/* No I\/O errors were encountered while writing the data file. *\/ DEBUG(D_receive) debug_printf(\"Data file written for message %s\\n\", message_id); \/* If there were any bad addresses extracted by -t, or there were no recipients left after -t, send a message to the sender of this message, or write it to stderr if the error handling option is set that way. Note that there may legitimately be no recipients for an SMTP message if they have all been removed by \"discard\". We need to rewind the data file in order to read it. In the case of no recipients or stderr error writing, throw the data file away afterwards, and exit. (This can't be SMTP, which always ensures there's at least one syntactically good recipient address.) *\/ if (extract_recip && (bad_addresses != NULL || recipients_count == 0)) { DEBUG(D_receive) { if (recipients_count == 0) debug_printf(\"*** No recipients\\n\"); if (bad_addresses != NULL) { error_block *eblock = bad_addresses; debug_printf(\"*** Bad address(es)\\n\"); while (eblock != NULL) { debug_printf(\" %s: %s\\n\", eblock->text1, eblock->text2); eblock = eblock->next; } } } fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); \/* If configured to send errors to the sender, but this fails, force a failure error code. We use a special one for no recipients so that it can be detected by the autoreply transport. Otherwise error_rc is set to errors_sender_rc, which is EXIT_FAILURE unless -oee was given, in which case it is EXIT_SUCCESS. *\/ if (error_handling == ERRORS_SENDER) { if (!moan_to_sender( (bad_addresses == NULL)? (extracted_ignored? ERRMESS_IGADDRESS : ERRMESS_NOADDRESS) : (recipients_list == NULL)? ERRMESS_BADNOADDRESS : ERRMESS_BADADDRESS, bad_addresses, header_list, data_file, FALSE)) error_rc = (bad_addresses == NULL)? EXIT_NORECIPIENTS : EXIT_FAILURE; } else { if (bad_addresses == NULL) { if (extracted_ignored) fprintf(stderr, \"exim: all -t recipients overridden by command line\\n\"); else fprintf(stderr, \"exim: no recipients in message\\n\"); } else { fprintf(stderr, \"exim: invalid address%s\", (bad_addresses->next == NULL)? \":\" : \"es:\\n\"); while (bad_addresses != NULL) { fprintf(stderr, \" %s: %s\\n\", bad_addresses->text1, bad_addresses->text2); bad_addresses = bad_addresses->next; } } } if (recipients_count == 0 || error_handling == ERRORS_STDERR) { Uunlink(spool_name); (void)fclose(data_file); exim_exit(error_rc, US\"receiving\"); } } \/* Data file successfully written. Generate text for the Received: header by expanding the configured string, and adding a timestamp. By leaving this operation till now, we ensure that the timestamp is the time that message reception was completed. However, this is deliberately done before calling the data ACL and local_scan(). This Received: header may therefore be inspected by the data ACL and by code in the local_scan() function. When they have run, we update the timestamp to be the final time of reception. If there is just one recipient, set up its value in the $received_for variable for use when we generate the Received: header. Note: the checking for too many Received: headers is handled by the delivery code. *\/ \/*XXX eventually add excess Received: check for cutthrough case back when classifying them *\/ if (received_header->text == NULL) \/* Non-cutthrough case *\/ { received_header_gen(); \/* Set the value of message_body_size for the DATA ACL and for local_scan() *\/ message_body_size = (fstat(data_fd, &statbuf) == 0)? statbuf.st_size - SPOOL_DATA_START_OFFSET : -1; \/* If an ACL from any RCPT commands set up any warning headers to add, do so now, before running the DATA ACL. *\/ add_acl_headers(ACL_WHERE_RCPT, US\"MAIL or RCPT\"); } else message_body_size = (fstat(data_fd, &statbuf) == 0)? statbuf.st_size - SPOOL_DATA_START_OFFSET : -1; \/* If an ACL is specified for checking things at this stage of reception of a message, run it, unless all the recipients were removed by \"discard\" in earlier ACLs. That is the only case in which recipients_count can be zero at this stage. Set deliver_datafile to point to the data file so that $message_body and $message_body_end can be extracted if needed. Allow $recipients in expansions. *\/ deliver_datafile = data_fd; user_msg = NULL; enable_dollar_recipients = TRUE; if (recipients_count == 0) blackholed_by = recipients_discarded ? US\"MAIL ACL\" : US\"RCPT ACL\"; else { \/* Handle interactive SMTP messages *\/ if (smtp_input && !smtp_batched_input) { #ifndef DISABLE_DKIM if (!dkim_disable_verify) { \/* Finish verification *\/ dkim_exim_verify_finish(); \/* Check if we must run the DKIM ACL *\/ if (acl_smtp_dkim && dkim_verify_signers && *dkim_verify_signers) { uschar * dkim_verify_signers_expanded = expand_string(dkim_verify_signers); gstring * results = NULL; int signer_sep = 0; const uschar * ptr; uschar * item; gstring * seen_items = NULL; int old_pool = store_pool; store_pool = POOL_PERM; \/* Allow created variables to live to data ACL *\/ if (!(ptr = dkim_verify_signers_expanded)) log_write(0, LOG_MAIN|LOG_PANIC, \"expansion of dkim_verify_signers option failed: %s\", expand_string_message); \/* Default to OK when no items are present *\/ rc = OK; while ((item = string_nextinlist(&ptr, &signer_sep, NULL, 0))) { \/* Prevent running ACL for an empty item *\/ if (!item || !*item) continue; \/* Only run ACL once for each domain or identity, no matter how often it appears in the expanded list. *\/ if (seen_items) { uschar * seen_item; const uschar * seen_items_list = string_from_gstring(seen_items); int seen_sep = ':'; BOOL seen_this_item = FALSE; while ((seen_item = string_nextinlist(&seen_items_list, &seen_sep, NULL, 0))) if (Ustrcmp(seen_item,item) == 0) { seen_this_item = TRUE; break; } if (seen_this_item) { DEBUG(D_receive) debug_printf(\"acl_smtp_dkim: skipping signer %s, \" \"already seen\\n\", item); continue; } seen_items = string_catn(seen_items, \":\", 1); } seen_items = string_cat(seen_items, item); rc = dkim_exim_acl_run(item, &results, &user_msg, &log_msg); if (rc != OK) { DEBUG(D_receive) debug_printf(\"acl_smtp_dkim: acl_check returned %d on %s, \" \"skipping remaining items\\n\", rc, item); cancel_cutthrough_connection(TRUE, US\"dkim acl not ok\"); break; } } dkim_verify_status = string_from_gstring(results); store_pool = old_pool; add_acl_headers(ACL_WHERE_DKIM, US\"DKIM\"); if (rc == DISCARD) { recipients_count = 0; blackholed_by = US\"DKIM ACL\"; if (log_msg) blackhole_log_msg = string_sprintf(\": %s\", log_msg); } else if (rc != OK) { Uunlink(spool_name); if (smtp_handle_acl_fail(ACL_WHERE_DKIM, rc, user_msg, log_msg) != 0) smtp_yield = FALSE; \/* No more messages after dropped connection *\/ smtp_reply = US\"\"; \/* Indicate reply already sent *\/ message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } } else dkim_exim_verify_log_all(); } #endif \/* DISABLE_DKIM *\/ #ifdef WITH_CONTENT_SCAN if (recipients_count > 0 && acl_smtp_mime != NULL && !run_mime_acl(acl_smtp_mime, &smtp_yield, &smtp_reply, &blackholed_by)) goto TIDYUP; #endif \/* WITH_CONTENT_SCAN *\/ #ifdef EXPERIMENTAL_DMARC dmarc_up = dmarc_store_data(from_header); #endif \/* EXPERIMENTAL_DMARC *\/ #ifndef DISABLE_PRDR if (prdr_requested && recipients_count > 1 && acl_smtp_data_prdr) { unsigned int c; int all_pass = OK; int all_fail = FAIL; smtp_printf(\"353 PRDR content analysis beginning\\r\\n\", TRUE); \/* Loop through recipients, responses must be in same order received *\/ for (c = 0; recipients_count > c; c++) { uschar * addr= recipients_list[c].address; uschar * msg= US\"PRDR R=<%s> %s\"; uschar * code; DEBUG(D_receive) debug_printf(\"PRDR processing recipient %s (%d of %d)\\n\", addr, c+1, recipients_count); rc = acl_check(ACL_WHERE_PRDR, addr, acl_smtp_data_prdr, &user_msg, &log_msg); \/* If any recipient rejected content, indicate it in final message *\/ all_pass |= rc; \/* If all recipients rejected, indicate in final message *\/ all_fail &= rc; switch (rc) { case OK: case DISCARD: code = US\"250\"; break; case DEFER: code = US\"450\"; break; default: code = US\"550\"; break; } if (user_msg != NULL) smtp_user_msg(code, user_msg); else { switch (rc) { case OK: case DISCARD: msg = string_sprintf(CS msg, addr, \"acceptance\"); break; case DEFER: msg = string_sprintf(CS msg, addr, \"temporary refusal\"); break; default: msg = string_sprintf(CS msg, addr, \"refusal\"); break; } smtp_user_msg(code, msg); } if (log_msg) log_write(0, LOG_MAIN, \"PRDR %s %s\", addr, log_msg); else if (user_msg) log_write(0, LOG_MAIN, \"PRDR %s %s\", addr, user_msg); else log_write(0, LOG_MAIN, \"%s\", CS msg); if (rc != OK) { receive_remove_recipient(addr); c--; } } \/* Set up final message, used if data acl gives OK *\/ smtp_reply = string_sprintf(\"%s id=%s message %s\", all_fail == FAIL ? US\"550\" : US\"250\", message_id, all_fail == FAIL ? US\"rejected for all recipients\" : all_pass == OK ? US\"accepted\" : US\"accepted for some recipients\"); if (recipients_count == 0) { message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; } } else prdr_requested = FALSE; #endif \/* !DISABLE_PRDR *\/ \/* Check the recipients count again, as the MIME ACL might have changed them. *\/ if (acl_smtp_data != NULL && recipients_count > 0) { rc = acl_check(ACL_WHERE_DATA, NULL, acl_smtp_data, &user_msg, &log_msg); add_acl_headers(ACL_WHERE_DATA, US\"DATA\"); if (rc == DISCARD) { recipients_count = 0; blackholed_by = US\"DATA ACL\"; if (log_msg) blackhole_log_msg = string_sprintf(\": %s\", log_msg); cancel_cutthrough_connection(TRUE, US\"data acl discard\"); } else if (rc != OK) { Uunlink(spool_name); cancel_cutthrough_connection(TRUE, US\"data acl not ok\"); #ifdef WITH_CONTENT_SCAN unspool_mbox(); #endif #ifdef EXPERIMENTAL_DCC dcc_ok = 0; #endif if (smtp_handle_acl_fail(ACL_WHERE_DATA, rc, user_msg, log_msg) != 0) smtp_yield = FALSE; \/* No more messages after dropped connection *\/ smtp_reply = US\"\"; \/* Indicate reply already sent *\/ message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; \/* Skip to end of function *\/ } } } \/* Handle non-SMTP and batch SMTP (i.e. non-interactive) messages. Note that we cannot take different actions for permanent and temporary rejections. *\/ else { #ifdef WITH_CONTENT_SCAN if (acl_not_smtp_mime != NULL && !run_mime_acl(acl_not_smtp_mime, &smtp_yield, &smtp_reply, &blackholed_by)) goto TIDYUP; #endif \/* WITH_CONTENT_SCAN *\/ if (acl_not_smtp != NULL) { uschar *user_msg, *log_msg; rc = acl_check(ACL_WHERE_NOTSMTP, NULL, acl_not_smtp, &user_msg, &log_msg); if (rc == DISCARD) { recipients_count = 0; blackholed_by = US\"non-SMTP ACL\"; if (log_msg != NULL) blackhole_log_msg = string_sprintf(\": %s\", log_msg); } else if (rc != OK) { Uunlink(spool_name); #ifdef WITH_CONTENT_SCAN unspool_mbox(); #endif #ifdef EXPERIMENTAL_DCC dcc_ok = 0; #endif \/* The ACL can specify where rejections are to be logged, possibly nowhere. The default is main and reject logs. *\/ if (log_reject_target != 0) log_write(0, log_reject_target, \"F=<%s> rejected by non-SMTP ACL: %s\", sender_address, log_msg); if (user_msg == NULL) user_msg = US\"local configuration problem\"; if (smtp_batched_input) { moan_smtp_batch(NULL, \"%d %s\", 550, user_msg); \/* Does not return *\/ } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_LOCAL_ACL, user_msg, US\"message rejected by non-SMTP ACL: \", error_rc, data_file, header_list); \/* Does not return *\/ } } add_acl_headers(ACL_WHERE_NOTSMTP, US\"non-SMTP\"); } } \/* The applicable ACLs have been run *\/ if (deliver_freeze) frozen_by = US\"ACL\"; \/* for later logging *\/ if (queue_only_policy) queued_by = US\"ACL\"; } #ifdef WITH_CONTENT_SCAN unspool_mbox(); #endif #ifdef EXPERIMENTAL_DCC dcc_ok = 0; #endif \/* The final check on the message is to run the scan_local() function. The version supplied with Exim always accepts, but this is a hook for sysadmins to supply their own checking code. The local_scan() function is run even when all the recipients have been discarded. *\/ \/*XXS could we avoid this for the standard case, given that few people will use it? *\/ lseek(data_fd, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); \/* Arrange to catch crashes in local_scan(), so that the -D file gets deleted, and the incident gets logged. *\/ os_non_restarting_signal(SIGSEGV, local_scan_crash_handler); os_non_restarting_signal(SIGFPE, local_scan_crash_handler); os_non_restarting_signal(SIGILL, local_scan_crash_handler); os_non_restarting_signal(SIGBUS, local_scan_crash_handler); DEBUG(D_receive) debug_printf(\"calling local_scan(); timeout=%d\\n\", local_scan_timeout); local_scan_data = NULL; os_non_restarting_signal(SIGALRM, local_scan_timeout_handler); if (local_scan_timeout > 0) alarm(local_scan_timeout); rc = local_scan(data_fd, &local_scan_data); alarm(0); os_non_restarting_signal(SIGALRM, sigalrm_handler); enable_dollar_recipients = FALSE; store_pool = POOL_MAIN; \/* In case changed *\/ DEBUG(D_receive) debug_printf(\"local_scan() returned %d %s\\n\", rc, local_scan_data); os_non_restarting_signal(SIGSEGV, SIG_DFL); os_non_restarting_signal(SIGFPE, SIG_DFL); os_non_restarting_signal(SIGILL, SIG_DFL); os_non_restarting_signal(SIGBUS, SIG_DFL); \/* The length check is paranoia against some runaway code, and also because (for a success return) lines in the spool file are read into big_buffer. *\/ if (local_scan_data != NULL) { int len = Ustrlen(local_scan_data); if (len > LOCAL_SCAN_MAX_RETURN) len = LOCAL_SCAN_MAX_RETURN; local_scan_data = string_copyn(local_scan_data, len); } if (rc == LOCAL_SCAN_ACCEPT_FREEZE) { if (!deliver_freeze) \/* ACL might have already frozen *\/ { deliver_freeze = TRUE; deliver_frozen_at = time(NULL); frozen_by = US\"local_scan()\"; } rc = LOCAL_SCAN_ACCEPT; } else if (rc == LOCAL_SCAN_ACCEPT_QUEUE) { if (!queue_only_policy) \/* ACL might have already queued *\/ { queue_only_policy = TRUE; queued_by = US\"local_scan()\"; } rc = LOCAL_SCAN_ACCEPT; } \/* Message accepted: remove newlines in local_scan_data because otherwise the spool file gets corrupted. Ensure that all recipients are qualified. *\/ if (rc == LOCAL_SCAN_ACCEPT) { if (local_scan_data != NULL) { uschar *s; for (s = local_scan_data; *s != 0; s++) if (*s == '\\n') *s = ' '; } for (i = 0; i < recipients_count; i++) { recipient_item *r = recipients_list + i; r->address = rewrite_address_qualify(r->address, TRUE); if (r->errors_to != NULL) r->errors_to = rewrite_address_qualify(r->errors_to, TRUE); } if (recipients_count == 0 && blackholed_by == NULL) blackholed_by = US\"local_scan\"; } \/* Message rejected: newlines permitted in local_scan_data to generate multiline SMTP responses. *\/ else { uschar *istemp = US\"\"; uschar *smtp_code; gstring * g; errmsg = local_scan_data; Uunlink(spool_name); \/* Cancel this message *\/ switch(rc) { default: log_write(0, LOG_MAIN, \"invalid return %d from local_scan(). Temporary \" \"rejection given\", rc); goto TEMPREJECT; case LOCAL_SCAN_REJECT_NOLOGHDR: BIT_CLEAR(log_selector, log_selector_size, Li_rejected_header); \/* Fall through *\/ case LOCAL_SCAN_REJECT: smtp_code = US\"550\"; if (errmsg == NULL) errmsg = US\"Administrative prohibition\"; break; case LOCAL_SCAN_TEMPREJECT_NOLOGHDR: BIT_CLEAR(log_selector, log_selector_size, Li_rejected_header); \/* Fall through *\/ case LOCAL_SCAN_TEMPREJECT: TEMPREJECT: smtp_code = US\"451\"; if (errmsg == NULL) errmsg = US\"Temporary local problem\"; istemp = US\"temporarily \"; break; } g = string_append(g, 2, US\"F=\", sender_address[0] == 0 ? US\"<>\" : sender_address); g = add_host_info_for_log(g); log_write(0, LOG_MAIN|LOG_REJECT, \"%s %srejected by local_scan(): %.256s\", string_from_gstring(g), istemp, string_printing(errmsg)); if (smtp_input) { if (!smtp_batched_input) { smtp_respond(smtp_code, 3, TRUE, errmsg); message_id[0] = 0; \/* Indicate no message accepted *\/ smtp_reply = US\"\"; \/* Indicate reply already sent *\/ goto TIDYUP; \/* Skip to end of function *\/ } else { moan_smtp_batch(NULL, \"%s %s\", smtp_code, errmsg); \/* Does not return *\/ } } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_LOCAL_SCAN, errmsg, US\"message rejected by local scan code: \", error_rc, data_file, header_list); \/* Does not return *\/ } } \/* Reset signal handlers to ignore signals that previously would have caused the message to be abandoned. *\/ signal(SIGTERM, SIG_IGN); signal(SIGINT, SIG_IGN); \/* Ensure the first time flag is set in the newly-received message. *\/ deliver_firsttime = TRUE; #ifdef EXPERIMENTAL_BRIGHTMAIL if (bmi_run == 1) { \/* rewind data file *\/ lseek(data_fd, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); bmi_verdicts = bmi_process_message(header_list, data_fd); } #endif \/* Update the timestamp in our Received: header to account for any time taken by an ACL or by local_scan(). The new time is the time that all reception processing is complete. *\/ timestamp = expand_string(US\"${tod_full}\"); tslen = Ustrlen(timestamp); memcpy(received_header->text + received_header->slen - tslen - 1, timestamp, tslen); \/* In MUA wrapper mode, ignore queueing actions set by ACL or local_scan() *\/ if (mua_wrapper) { deliver_freeze = FALSE; queue_only_policy = FALSE; } \/* Keep the data file open until we have written the header file, in order to hold onto the lock. In a -bh run, or if the message is to be blackholed, we don't write the header file, and we unlink the data file. If writing the header file fails, we have failed to accept this message. *\/ if (host_checking || blackholed_by != NULL) { header_line *h; Uunlink(spool_name); msg_size = 0; \/* Compute size for log line *\/ for (h = header_list; h != NULL; h = h->next) if (h->type != '*') msg_size += h->slen; } \/* Write the -H file *\/ else if ((msg_size = spool_write_header(message_id, SW_RECEIVING, &errmsg)) < 0) { log_write(0, LOG_MAIN, \"Message abandoned: %s\", errmsg); Uunlink(spool_name); \/* Lose the data file *\/ if (smtp_input) { smtp_reply = US\"451 Error in writing spool file\"; message_id[0] = 0; \/* Indicate no message accepted *\/ goto TIDYUP; } else { fseek(data_file, (long int)SPOOL_DATA_START_OFFSET, SEEK_SET); give_local_error(ERRMESS_IOERR, errmsg, US\"\", error_rc, data_file, header_list); \/* Does not return *\/ } } \/* The message has now been successfully received. *\/ receive_messagecount++; \/* In SMTP sessions we may receive several in one connection. After each one, we wait for the clock to tick at the level of message-id granularity. This is so that the combination of time+pid is unique, even on systems where the pid can be re-used within our time interval. We can't shorten the interval without re-designing the message-id. See comments above where the message id is created. This is Something For The Future. *\/ message_id_tv.tv_usec = (message_id_tv.tv_usec\/id_resolution) * id_resolution; exim_wait_tick(&message_id_tv, id_resolution); \/* Add data size to written header size. We do not count the initial file name that is in the file, but we do add one extra for the notional blank line that precedes the data. This total differs from message_size in that it include the added Received: header and any other headers that got created locally. *\/ fflush(data_file); fstat(data_fd, &statbuf); msg_size += statbuf.st_size - SPOOL_DATA_START_OFFSET + 1; \/* Generate a \"message received\" log entry. We do this by building up a dynamic string as required. Since we commonly want to add two items at a time, use a macro to simplify the coding. We log the arrival of a new message while the file is still locked, just in case the machine is *really* fast, and delivers it first! Include any message id that is in the message - since the syntax of a message id is actually an addr-spec, we can use the parse routine to canonicalize it. *\/ g = string_get(256); g = string_append(g, 2, fake_response == FAIL ? US\"(= \" : US\"<= \", sender_address[0] == 0 ? US\"<>\" : sender_address); if (message_reference) g = string_append(g, 2, US\" R=\", message_reference); g = add_host_info_for_log(g); #ifdef SUPPORT_TLS if (LOGGING(tls_cipher) && tls_in.cipher) g = string_append(g, 2, US\" X=\", tls_in.cipher); if (LOGGING(tls_certificate_verified) && tls_in.cipher) g = string_append(g, 2, US\" CV=\", tls_in.certificate_verified ? \"yes\":\"no\"); if (LOGGING(tls_peerdn) && tls_in.peerdn) g = string_append(g, 3, US\" DN=\\\"\", string_printing(tls_in.peerdn), US\"\\\"\"); if (LOGGING(tls_sni) && tls_in.sni) g = string_append(g, 3, US\" SNI=\\\"\", string_printing(tls_in.sni), US\"\\\"\"); #endif if (sender_host_authenticated) { g = string_append(g, 2, US\" A=\", sender_host_authenticated); if (authenticated_id) { g = string_append(g, 2, US\":\", authenticated_id); if (LOGGING(smtp_mailauth) && authenticated_sender) g = string_append(g, 2, US\":\", authenticated_sender); } } #ifndef DISABLE_PRDR if (prdr_requested) g = string_catn(g, US\" PRDR\", 5); #endif #ifdef SUPPORT_PROXY if (proxy_session && LOGGING(proxy)) g = string_append(g, 2, US\" PRX=\", proxy_local_address); #endif if (chunking_state > CHUNKING_OFFERED) g = string_catn(g, US\" K\", 2); sprintf(CS big_buffer, \"%d\", msg_size); g = string_append(g, 2, US\" S=\", big_buffer); \/* log 8BITMIME mode announced in MAIL_FROM 0 ... no BODY= used 7 ... 7BIT 8 ... 8BITMIME *\/ if (LOGGING(8bitmime)) { sprintf(CS big_buffer, \"%d\", body_8bitmime); g = string_append(g, 2, US\" M8S=\", big_buffer); } if (*queue_name) g = string_append(g, 2, US\" Q=\", queue_name); \/* If an addr-spec in a message-id contains a quoted string, it can contain any characters except \" \\ and CR and so in particular it can contain NL! Therefore, make sure we use a printing-characters only version for the log. Also, allow for domain literals in the message id. *\/ if (msgid_header) { uschar *old_id; BOOL save_allow_domain_literals = allow_domain_literals; allow_domain_literals = TRUE; old_id = parse_extract_address(Ustrchr(msgid_header->text, ':') + 1, &errmsg, &start, &end, &domain, FALSE); allow_domain_literals = save_allow_domain_literals; if (old_id != NULL) g = string_append(g, 2, US\" id=\", string_printing(old_id)); } \/* If subject logging is turned on, create suitable printing-character text. By expanding $h_subject: we make use of the MIME decoding. *\/ if (LOGGING(subject) && subject_header != NULL) { int i; uschar *p = big_buffer; uschar *ss = expand_string(US\"$h_subject:\"); \/* Backslash-quote any double quotes or backslashes so as to make a a C-like string, and turn any non-printers into escape sequences. *\/ *p++ = '\\\"'; if (*ss != 0) for (i = 0; i < 100 && ss[i] != 0; i++) { if (ss[i] == '\\\"' || ss[i] == '\\\\') *p++ = '\\\\'; *p++ = ss[i]; } *p++ = '\\\"'; *p = 0; g = string_append(g, 2, US\" T=\", string_printing(big_buffer)); } \/* Terminate the string: string_cat() and string_append() leave room, but do not put the zero in. *\/ (void) string_from_gstring(g); \/* Create a message log file if message logs are being used and this message is not blackholed. Write the reception stuff to it. We used to leave message log creation until the first delivery, but this has proved confusing for some people. *\/ if (message_logs && !blackholed_by) { int fd; spool_name = spool_fname(US\"msglog\", message_subdir, message_id, US\"\"); if ( (fd = Uopen(spool_name, O_WRONLY|O_APPEND|O_CREAT, SPOOL_MODE)) < 0 && errno == ENOENT ) { (void)directory_make(spool_directory, spool_sname(US\"msglog\", message_subdir), MSGLOG_DIRECTORY_MODE, TRUE); fd = Uopen(spool_name, O_WRONLY|O_APPEND|O_CREAT, SPOOL_MODE); } if (fd < 0) log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't open message log %s: %s\", spool_name, strerror(errno)); else { FILE *message_log = fdopen(fd, \"a\"); if (message_log == NULL) { log_write(0, LOG_MAIN|LOG_PANIC, \"Couldn't fdopen message log %s: %s\", spool_name, strerror(errno)); (void)close(fd); } else { uschar *now = tod_stamp(tod_log); fprintf(message_log, \"%s Received from %s\\n\", now, g->s+3); if (deliver_freeze) fprintf(message_log, \"%s frozen by %s\\n\", now, frozen_by); if (queue_only_policy) fprintf(message_log, \"%s no immediate delivery: queued%s%s by %s\\n\", now, *queue_name ? \" in \" : \"\", *queue_name ? CS queue_name : \"\", queued_by); (void)fclose(message_log); } } } \/* Everything has now been done for a successful message except logging its arrival, and outputting an SMTP response. While writing to the log, set a flag to cause a call to receive_bomb_out() if the log cannot be opened. *\/ receive_call_bombout = TRUE; \/* Before sending an SMTP response in a TCP\/IP session, we check to see if the connection has gone away. This can only be done if there is no unconsumed input waiting in the local input buffer. We can test for this by calling receive_smtp_buffered(). RFC 2920 (pipelining) explicitly allows for additional input to be sent following the final dot, so the presence of following input is not an error. If the connection is still present, but there is no unread input for the socket, the result of a select() call will be zero. If, however, the connection has gone away, or if there is pending input, the result of select() will be non-zero. The two cases can be distinguished by trying to read the next input character. If we succeed, we can unread it so that it remains in the local buffer for handling later. If not, the connection has been lost. Of course, since TCP\/IP is asynchronous, there is always a chance that the connection will vanish between the time of this test and the sending of the response, but the chance of this happening should be small. *\/ if (smtp_input && sender_host_address != NULL && !sender_host_notsocket && !receive_smtp_buffered()) { struct timeval tv; fd_set select_check; FD_ZERO(&select_check); FD_SET(fileno(smtp_in), &select_check); tv.tv_sec = 0; tv.tv_usec = 0; if (select(fileno(smtp_in) + 1, &select_check, NULL, NULL, &tv) != 0) { int c = (receive_getc)(GETC_BUFFER_UNLIMITED); if (c != EOF) (receive_ungetc)(c); else { smtp_notquit_exit(US\"connection-lost\", NULL, NULL); smtp_reply = US\"\"; \/* No attempt to send a response *\/ smtp_yield = FALSE; \/* Nothing more on this connection *\/ \/* Re-use the log line workspace *\/ g->ptr = 0; g = string_cat(g, US\"SMTP connection lost after final dot\"); g = add_host_info_for_log(g); log_write(0, LOG_MAIN, \"%s\", string_from_gstring(g)); \/* Delete the files for this aborted message. *\/ Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-H\")); Uunlink(spool_fname(US\"msglog\", message_subdir, message_id, US\"\")); goto TIDYUP; } } } \/* The connection has not gone away; we really are going to take responsibility for this message. *\/ \/* Cutthrough - had sender last-dot; assume we've sent (or bufferred) all data onward by now. Send dot onward. If accepted, wipe the spooled files, log as delivered and accept the sender's dot (below). If rejected: copy response to sender, wipe the spooled files, log appropriately. If temp-reject: normally accept to sender, keep the spooled file - unless defer=pass in which case pass temp-reject back to initiator and dump the files. Having the normal spool files lets us do data-filtering, and store\/forward on temp-reject. XXX We do not handle queue-only, freezing, or blackholes. *\/ if(cutthrough.fd >= 0 && cutthrough.delivery) { uschar * msg = cutthrough_finaldot(); \/* Ask the target system to accept the message *\/ \/* Logging was done in finaldot() *\/ switch(msg[0]) { case '2': \/* Accept. Do the same to the source; dump any spoolfiles. *\/ cutthrough_done = ACCEPTED; break; \/* message_id needed for SMTP accept below *\/ case '4': \/* Temp-reject. Keep spoolfiles and accept, unless defer-pass mode. ... for which, pass back the exact error *\/ if (cutthrough.defer_pass) smtp_reply = string_copy_malloc(msg); \/*FALLTRHOUGH*\/ default: \/* Unknown response, or error. Treat as temp-reject. *\/ cutthrough_done = TMP_REJ; \/* Avoid the usual immediate delivery attempt *\/ break; \/* message_id needed for SMTP accept below *\/ case '5': \/* Perm-reject. Do the same to the source. Dump any spoolfiles *\/ smtp_reply = string_copy_malloc(msg); \/* Pass on the exact error *\/ cutthrough_done = PERM_REJ; break; } } #ifndef DISABLE_PRDR if(!smtp_reply || prdr_requested) #else if(!smtp_reply) #endif { log_write(0, LOG_MAIN | (LOGGING(received_recipients)? LOG_RECIPIENTS : 0) | (LOGGING(received_sender)? LOG_SENDER : 0), \"%s\", g->s); \/* Log any control actions taken by an ACL or local_scan(). *\/ if (deliver_freeze) log_write(0, LOG_MAIN, \"frozen by %s\", frozen_by); if (queue_only_policy) log_write(L_delay_delivery, LOG_MAIN, \"no immediate delivery: queued%s%s by %s\", *queue_name ? \" in \" : \"\", *queue_name ? CS queue_name : \"\", queued_by); } receive_call_bombout = FALSE; store_reset(g); \/* The store for the main log message can be reused *\/ \/* If the message is frozen, and freeze_tell is set, do the telling. *\/ if (deliver_freeze && freeze_tell != NULL && freeze_tell[0] != 0) { moan_tell_someone(freeze_tell, NULL, US\"Message frozen on arrival\", \"Message %s was frozen on arrival by %s.\\nThe sender is <%s>.\\n\", message_id, frozen_by, sender_address); } \/* Either a message has been successfully received and written to the two spool files, or an error in writing the spool has occurred for an SMTP message, or an SMTP message has been rejected for policy reasons. (For a non-SMTP message we will have already given up because there's no point in carrying on!) In either event, we must now close (and thereby unlock) the data file. In the successful case, this leaves the message on the spool, ready for delivery. In the error case, the spool file will be deleted. Then tidy up store, interact with an SMTP call if necessary, and return. A fflush() was done earlier in the expectation that any write errors on the data file will be flushed(!) out thereby. Nevertheless, it is theoretically possible for fclose() to fail - but what to do? What has happened to the lock if this happens? *\/ TIDYUP: process_info[process_info_len] = 0; \/* Remove message id *\/ if (data_file != NULL) (void)fclose(data_file); \/* Frees the lock *\/ \/* Now reset signal handlers to their defaults *\/ signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL); \/* Tell an SMTP caller the state of play, and arrange to return the SMTP return value, which defaults TRUE - meaning there may be more incoming messages from this connection. For non-SMTP callers (where there is only ever one message), the default is FALSE. *\/ if (smtp_input) { yield = smtp_yield; \/* Handle interactive SMTP callers. After several kinds of error, smtp_reply is set to the response that should be sent. When it is NULL, we generate default responses. After an ACL error or local_scan() error, the response has already been sent, and smtp_reply is an empty string to indicate this. *\/ if (!smtp_batched_input) { if (!smtp_reply) { if (fake_response != OK) smtp_respond(fake_response == DEFER ? US\"450\" : US\"550\", 3, TRUE, fake_response_text); \/* An OK response is required; use \"message\" text if present. *\/ else if (user_msg) { uschar *code = US\"250\"; int len = 3; smtp_message_code(&code, &len, &user_msg, NULL, TRUE); smtp_respond(code, len, TRUE, user_msg); } \/* Default OK response *\/ else if (chunking_state > CHUNKING_OFFERED) { smtp_printf(\"250- %u byte chunk, total %d\\r\\n250 OK id=%s\\r\\n\", FALSE, chunking_datasize, message_size+message_linecount, message_id); chunking_state = CHUNKING_OFFERED; } else smtp_printf(\"250 OK id=%s\\r\\n\", FALSE, message_id); if (host_checking) fprintf(stdout, \"\\n**** SMTP testing: that is not a real message id!\\n\\n\"); } \/* smtp_reply is set non-empty *\/ else if (smtp_reply[0] != 0) if (fake_response != OK && (smtp_reply[0] == '2')) smtp_respond((fake_response == DEFER)? US\"450\" : US\"550\", 3, TRUE, fake_response_text); else smtp_printf(\"%.1024s\\r\\n\", FALSE, smtp_reply); switch (cutthrough_done) { case ACCEPTED: log_write(0, LOG_MAIN, \"Completed\");\/* Delivery was done *\/ case PERM_REJ: \/* Delete spool files *\/ Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-H\")); Uunlink(spool_fname(US\"msglog\", message_subdir, message_id, US\"\")); break; case TMP_REJ: if (cutthrough.defer_pass) { Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-D\")); Uunlink(spool_fname(US\"input\", message_subdir, message_id, US\"-H\")); Uunlink(spool_fname(US\"msglog\", message_subdir, message_id, US\"\")); } default: break; } if (cutthrough_done != NOT_TRIED) { message_id[0] = 0; \/* Prevent a delivery from starting *\/ cutthrough.delivery = cutthrough.callout_hold_only = FALSE; cutthrough.defer_pass = FALSE; } } \/* For batched SMTP, generate an error message on failure, and do nothing on success. The function moan_smtp_batch() does not return - it exits from the program with a non-zero return code. *\/ else if (smtp_reply) moan_smtp_batch(NULL, \"%s\", smtp_reply); } \/* If blackholing, we can immediately log this message's sad fate. The data file has already been unlinked, and the header file was never written to disk. We must now indicate that nothing was received, to prevent a delivery from starting. *\/ if (blackholed_by) { const uschar *detail = local_scan_data ? string_printing(local_scan_data) : string_sprintf(\"(%s discarded recipients)\", blackholed_by); log_write(0, LOG_MAIN, \"=> blackhole %s%s\", detail, blackhole_log_msg); log_write(0, LOG_MAIN, \"Completed\"); message_id[0] = 0; } \/* Reset headers so that logging of rejects for a subsequent message doesn't include them. It is also important to set header_last = NULL before exiting from this function, as this prevents certain rewrites that might happen during subsequent verifying (of another incoming message) from trying to add headers when they shouldn't. *\/ header_list = header_last = NULL; return yield; \/* TRUE if more messages (SMTP only) *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":81180,"input":"static MagickBooleanType CLISimpleOperatorImage(MagickCLI *cli_wand, const char *option, const char *arg1n, const char *arg2n, ExceptionInfo *exception) { Image * new_image; GeometryInfo geometry_info; RectangleInfo geometry; MagickStatusType flags; ssize_t parse; const char \/* percent escaped versions of the args *\/ *arg1, *arg2; #define _image_info (cli_wand->wand.image_info) #define _image (cli_wand->wand.images) #define _exception (cli_wand->wand.exception) #define _draw_info (cli_wand->draw_info) #define _quantize_info (cli_wand->quantize_info) #define _process_flags (cli_wand->process_flags) #define _option_type ((CommandOptionFlags) cli_wand->command->flags) #define IfNormalOp (*option=='-') #define IfPlusOp (*option!='-') #define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse #define IsPlusOp IfNormalOp ? MagickFalse : MagickTrue assert(cli_wand != (MagickCLI *) NULL); assert(cli_wand->signature == MagickWandSignature); assert(cli_wand->wand.signature == MagickWandSignature); assert(_image != (Image *) NULL); \/* an image must be present *\/ if (cli_wand->wand.debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),\"%s\",cli_wand->wand.name); arg1 = arg1n, arg2 = arg2n; \/* Interpret Percent Escapes in Arguments - using first image *\/ if ( (((_process_flags & ProcessInterpretProperities) != 0 ) || ((_option_type & AlwaysInterpretArgsFlag) != 0) ) && ((_option_type & NeverInterpretArgsFlag) == 0) ) { \/* Interpret Percent escapes in argument 1 *\/ if (arg1n != (char *) NULL) { arg1=InterpretImageProperties(_image_info,_image,arg1n,_exception); if (arg1 == (char *) NULL) { CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option); arg1=arg1n; \/* use the given argument as is *\/ } } if (arg2n != (char *) NULL) { arg2=InterpretImageProperties(_image_info,_image,arg2n,_exception); if (arg2 == (char *) NULL) { CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option); arg2=arg2n; \/* use the given argument as is *\/ } } } #undef _process_flags #undef _option_type #if 0 (void) FormatLocaleFile(stderr, \"CLISimpleOperatorImage: \\\"%s\\\" \\\"%s\\\" \\\"%s\\\"\\n\",option,arg1,arg2); #endif new_image = (Image *) NULL; \/* the replacement image, if not null at end *\/ SetGeometryInfo(&geometry_info); switch (*(option+1)) { case 'a': { if (LocaleCompare(\"adaptive-blur\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; new_image=AdaptiveBlurImage(_image,geometry_info.rho, geometry_info.sigma,_exception); break; } if (LocaleCompare(\"adaptive-resize\",option+1) == 0) { \/* FUTURE: Roll into a resize special operator *\/ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParseRegionGeometry(_image,arg1,&geometry,_exception); new_image=AdaptiveResizeImage(_image,geometry.width,geometry.height, _exception); break; } if (LocaleCompare(\"adaptive-sharpen\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; new_image=AdaptiveSharpenImage(_image,geometry_info.rho, geometry_info.sigma,_exception); break; } if (LocaleCompare(\"alpha\",option+1) == 0) { parse=ParseCommandOption(MagickAlphaChannelOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,\"UnrecognizedAlphaChannelOption\", option,arg1); (void) SetImageAlphaChannel(_image,(AlphaChannelOption) parse, _exception); break; } if (LocaleCompare(\"annotate\",option+1) == 0) { char geometry[MagickPathExtent]; SetGeometryInfo(&geometry_info); flags=ParseGeometry(arg1,&geometry_info); if (flags == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) CloneString(&_draw_info->text,arg2); (void) FormatLocaleString(geometry,MagickPathExtent,\"%+f%+f\", geometry_info.xi,geometry_info.psi); (void) CloneString(&_draw_info->geometry,geometry); _draw_info->affine.sx=cos(DegreesToRadians( fmod(geometry_info.rho,360.0))); _draw_info->affine.rx=sin(DegreesToRadians( fmod(geometry_info.rho,360.0))); _draw_info->affine.ry=(-sin(DegreesToRadians( fmod(geometry_info.sigma,360.0)))); _draw_info->affine.sy=cos(DegreesToRadians( fmod(geometry_info.sigma,360.0))); (void) AnnotateImage(_image,_draw_info,_exception); GetAffineMatrix(&_draw_info->affine); break; } if (LocaleCompare(\"auto-gamma\",option+1) == 0) { (void) AutoGammaImage(_image,_exception); break; } if (LocaleCompare(\"auto-level\",option+1) == 0) { (void) AutoLevelImage(_image,_exception); break; } if (LocaleCompare(\"auto-orient\",option+1) == 0) { new_image=AutoOrientImage(_image,_image->orientation,_exception); break; } if (LocaleCompare(\"auto-threshold\",option+1) == 0) { AutoThresholdMethod method; method=(AutoThresholdMethod) ParseCommandOption( MagickAutoThresholdOptions,MagickFalse,arg1); (void) AutoThresholdImage(_image,method,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'b': { if (LocaleCompare(\"black-threshold\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) BlackThresholdImage(_image,arg1,_exception); break; } if (LocaleCompare(\"blue-shift\",option+1) == 0) { geometry_info.rho=1.5; if (IfNormalOp) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); } new_image=BlueShiftImage(_image,geometry_info.rho,_exception); break; } if (LocaleCompare(\"blur\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; new_image=BlurImage(_image,geometry_info.rho,geometry_info.sigma, _exception); break; } if (LocaleCompare(\"border\",option+1) == 0) { CompositeOperator compose; const char* value; flags=ParsePageGeometry(_image,arg1,&geometry,_exception); if ((flags & (WidthValue | HeightValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); compose=OverCompositeOp; value=GetImageOption(_image_info,\"compose\"); if (value != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,value); new_image=BorderImage(_image,&geometry,compose,_exception); break; } if (LocaleCompare(\"brightness-contrast\",option+1) == 0) { double brightness, contrast; GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); brightness=geometry_info.rho; contrast=0.0; if ((flags & SigmaValue) != 0) contrast=geometry_info.sigma; (void) BrightnessContrastImage(_image,brightness,contrast, _exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'c': { if (LocaleCompare(\"canny\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=10; if ((flags & PsiValue) == 0) geometry_info.psi=30; if ((flags & PercentValue) != 0) { geometry_info.xi\/=100.0; geometry_info.psi\/=100.0; } new_image=CannyEdgeImage(_image,geometry_info.rho,geometry_info.sigma, geometry_info.xi,geometry_info.psi,_exception); break; } if (LocaleCompare(\"cdl\",option+1) == 0) { char *color_correction_collection; \/* Note: arguments do not have percent escapes expanded *\/ \/* Color correct with a color decision list. *\/ color_correction_collection=FileToString(arg1,~0UL,_exception); if (color_correction_collection == (char *) NULL) break; (void) ColorDecisionListImage(_image,color_correction_collection, _exception); break; } if (LocaleCompare(\"channel\",option+1) == 0) { if (IfPlusOp) { (void) SetPixelChannelMask(_image,DefaultChannels); break; } parse=ParseChannelOption(arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,\"UnrecognizedChannelType\",option, arg1); (void) SetPixelChannelMask(_image,(ChannelType) parse); break; } if (LocaleCompare(\"charcoal\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=1.0; new_image=CharcoalImage(_image,geometry_info.rho,geometry_info.sigma, _exception); break; } if (LocaleCompare(\"chop\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParseGravityGeometry(_image,arg1,&geometry,_exception); new_image=ChopImage(_image,&geometry,_exception); break; } if (LocaleCompare(\"clahe\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParseGeometry(arg1,&geometry_info); flags=ParseRegionGeometry(_image,arg1,&geometry,_exception); (void) CLAHEImage(_image,geometry.width,geometry.height, (size_t) geometry.x,geometry_info.psi,_exception); break; } if (LocaleCompare(\"clamp\",option+1) == 0) { (void) ClampImage(_image,_exception); break; } if (LocaleCompare(\"clip\",option+1) == 0) { if (IfNormalOp) (void) ClipImage(_image,_exception); else \/* \"+mask\" remove the write mask *\/ (void) SetImageMask(_image,WritePixelMask,(Image *) NULL, _exception); break; } if (LocaleCompare(\"clip-mask\",option+1) == 0) { Image *clip_mask; if (IfPlusOp) { \/* use \"+clip-mask\" Remove the write mask for -clip-path *\/ (void) SetImageMask(_image,WritePixelMask,(Image *) NULL,_exception); break; } clip_mask=GetImageCache(_image_info,arg1,_exception); if (clip_mask == (Image *) NULL) break; (void) SetImageMask(_image,WritePixelMask,clip_mask,_exception); clip_mask=DestroyImage(clip_mask); break; } if (LocaleCompare(\"clip-path\",option+1) == 0) { (void) ClipImagePath(_image,arg1,IsNormalOp,_exception); \/* Note: Use \"+clip-mask\" remove the write mask added *\/ break; } if (LocaleCompare(\"colorize\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=ColorizeImage(_image,arg1,&_draw_info->fill,_exception); break; } if (LocaleCompare(\"color-matrix\",option+1) == 0) { KernelInfo *kernel; kernel=AcquireKernelInfo(arg1,exception); if (kernel == (KernelInfo *) NULL) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=ColorMatrixImage(_image,kernel,_exception); kernel=DestroyKernelInfo(kernel); break; } if (LocaleCompare(\"colors\",option+1) == 0) { \/* Reduce the number of colors in the image. FUTURE: also provide 'plus version with image 'color counts' *\/ _quantize_info->number_colors=StringToUnsignedLong(arg1); if (_quantize_info->number_colors == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((_image->storage_class == DirectClass) || _image->colors > _quantize_info->number_colors) (void) QuantizeImage(_quantize_info,_image,_exception); else (void) CompressImageColormap(_image,_exception); break; } if (LocaleCompare(\"colorspace\",option+1) == 0) { \/* WARNING: this is both a image_info setting (already done) and a operator to change image colorspace. FUTURE: default colorspace should be sRGB! Unless some type of 'linear colorspace' mode is set. Note that +colorspace sets \"undefined\" or no effect on new images, but forces images already in memory back to RGB! That seems to be a little strange! *\/ (void) TransformImageColorspace(_image, IfNormalOp ? _image_info->colorspace : sRGBColorspace, _exception); break; } if (LocaleCompare(\"connected-components\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=ConnectedComponentsImage(_image,(size_t) StringToInteger(arg1),(CCObjectInfo **) NULL,_exception); break; } if (LocaleCompare(\"contrast\",option+1) == 0) { CLIWandWarnReplaced(IfNormalOp?\"-level\":\"+level\"); (void) ContrastImage(_image,IsNormalOp,_exception); break; } if (LocaleCompare(\"contrast-stretch\",option+1) == 0) { double black_point, white_point; MagickStatusType flags; flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); black_point=geometry_info.rho; white_point=(flags & SigmaValue) != 0 ? geometry_info.sigma : black_point; if ((flags & PercentValue) != 0) { black_point*=(double) _image->columns*_image->rows\/100.0; white_point*=(double) _image->columns*_image->rows\/100.0; } white_point=(double) _image->columns*_image->rows-white_point; (void) ContrastStretchImage(_image,black_point,white_point, _exception); break; } if (LocaleCompare(\"convolve\",option+1) == 0) { double gamma; KernelInfo *kernel_info; register ssize_t j; kernel_info=AcquireKernelInfo(arg1,exception); if (kernel_info == (KernelInfo *) NULL) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); gamma=0.0; for (j=0; j < (ssize_t) (kernel_info->width*kernel_info->height); j++) gamma+=kernel_info->values[j]; gamma=1.0\/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma); for (j=0; j < (ssize_t) (kernel_info->width*kernel_info->height); j++) kernel_info->values[j]*=gamma; new_image=MorphologyImage(_image,CorrelateMorphology,1,kernel_info, _exception); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare(\"crop\",option+1) == 0) { \/* WARNING: This can generate multiple images! *\/ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=CropImageToTiles(_image,arg1,_exception); break; } if (LocaleCompare(\"cycle\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) CycleColormapImage(_image,(ssize_t) StringToLong(arg1), _exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'd': { if (LocaleCompare(\"decipher\",option+1) == 0) { \/* Note: arguments do not have percent escapes expanded *\/ StringInfo *passkey; passkey=FileToStringInfo(arg1,~0UL,_exception); if (passkey == (StringInfo *) NULL) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) PasskeyDecipherImage(_image,passkey,_exception); passkey=DestroyStringInfo(passkey); break; } if (LocaleCompare(\"depth\",option+1) == 0) { \/* The _image_info->depth setting has already been set We just need to apply it to all images in current sequence WARNING: Depth from 8 to 16 causes 'quantum rounding to images! That is it really is an operation, not a setting! Arrgghhh FUTURE: this should not be an operator!!! *\/ (void) SetImageDepth(_image,_image_info->depth,_exception); break; } if (LocaleCompare(\"deskew\",option+1) == 0) { double threshold; if (IfNormalOp) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); threshold=StringToDoubleInterval(arg1,(double) QuantumRange+1.0); } else threshold=40.0*QuantumRange\/100.0; new_image=DeskewImage(_image,threshold,_exception); break; } if (LocaleCompare(\"despeckle\",option+1) == 0) { new_image=DespeckleImage(_image,_exception); break; } if (LocaleCompare(\"distort\",option+1) == 0) { double *args; ssize_t count; parse = ParseCommandOption(MagickDistortOptions,MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedDistortMethod\", option,arg1); if ((DistortMethod) parse == ResizeDistortion) { double resize_args[2]; \/* Special Case - Argument is actually a resize geometry! ** Convert that to an appropriate distortion argument array. ** FUTURE: make a separate special resize operator Roll into a resize special operator *\/ if (IsGeometry(arg2) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidGeometry\", option,arg2); (void) ParseRegionGeometry(_image,arg2,&geometry,_exception); resize_args[0]=(double) geometry.width; resize_args[1]=(double) geometry.height; new_image=DistortImage(_image,(DistortMethod) parse, (size_t)2,resize_args,MagickTrue,_exception); break; } \/* convert argument string into an array of doubles *\/ args = StringToArrayOfDoubles(arg2,&count,_exception); if (args == (double *) NULL ) CLIWandExceptArgBreak(OptionError,\"InvalidNumberList\",option,arg2); new_image=DistortImage(_image,(DistortMethod) parse,(size_t) count,args,IsPlusOp,_exception); args=(double *) RelinquishMagickMemory(args); break; } if (LocaleCompare(\"draw\",option+1) == 0) { (void) CloneString(&_draw_info->primitive,arg1); (void) DrawImage(_image,_draw_info,_exception); (void) CloneString(&_draw_info->primitive,(char *) NULL); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'e': { if (LocaleCompare(\"edge\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=EdgeImage(_image,geometry_info.rho,_exception); break; } if (LocaleCompare(\"emboss\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; new_image=EmbossImage(_image,geometry_info.rho, geometry_info.sigma,_exception); break; } if (LocaleCompare(\"encipher\",option+1) == 0) { \/* Note: arguments do not have percent escapes expanded *\/ StringInfo *passkey; passkey=FileToStringInfo(arg1,~0UL,_exception); if (passkey != (StringInfo *) NULL) { (void) PasskeyEncipherImage(_image,passkey,_exception); passkey=DestroyStringInfo(passkey); } break; } if (LocaleCompare(\"enhance\",option+1) == 0) { new_image=EnhanceImage(_image,_exception); break; } if (LocaleCompare(\"equalize\",option+1) == 0) { (void) EqualizeImage(_image,_exception); break; } if (LocaleCompare(\"evaluate\",option+1) == 0) { double constant; parse = ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedEvaluateOperator\", option,arg1); if (IsGeometry(arg2) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg2); constant=StringToDoubleInterval(arg2,(double) QuantumRange+1.0); (void) EvaluateImage(_image,(MagickEvaluateOperator)parse,constant, _exception); break; } if (LocaleCompare(\"extent\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParseGravityGeometry(_image,arg1,&geometry,_exception); if (geometry.width == 0) geometry.width=_image->columns; if (geometry.height == 0) geometry.height=_image->rows; new_image=ExtentImage(_image,&geometry,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'f': { if (LocaleCompare(\"flip\",option+1) == 0) { new_image=FlipImage(_image,_exception); break; } if (LocaleCompare(\"flop\",option+1) == 0) { new_image=FlopImage(_image,_exception); break; } if (LocaleCompare(\"floodfill\",option+1) == 0) { PixelInfo target; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParsePageGeometry(_image,arg1,&geometry,_exception); (void) QueryColorCompliance(arg2,AllCompliance,&target,_exception); (void) FloodfillPaintImage(_image,_draw_info,&target,geometry.x, geometry.y,IsPlusOp,_exception); break; } if (LocaleCompare(\"frame\",option+1) == 0) { FrameInfo frame_info; CompositeOperator compose; const char* value; value=GetImageOption(_image_info,\"compose\"); compose=OverCompositeOp; \/* use Over not _image->compose *\/ if (value != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParsePageGeometry(_image,arg1,&geometry,_exception); frame_info.width=geometry.width; frame_info.height=geometry.height; frame_info.outer_bevel=geometry.x; frame_info.inner_bevel=geometry.y; frame_info.x=(ssize_t) frame_info.width; frame_info.y=(ssize_t) frame_info.height; frame_info.width=_image->columns+2*frame_info.width; frame_info.height=_image->rows+2*frame_info.height; new_image=FrameImage(_image,&frame_info,compose,_exception); break; } if (LocaleCompare(\"function\",option+1) == 0) { double *args; ssize_t count; parse=ParseCommandOption(MagickFunctionOptions,MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedFunction\", option,arg1); \/* convert argument string into an array of doubles *\/ args = StringToArrayOfDoubles(arg2,&count,_exception); if (args == (double *) NULL ) CLIWandExceptArgBreak(OptionError,\"InvalidNumberList\",option,arg2); (void) FunctionImage(_image,(MagickFunction)parse,(size_t) count,args, _exception); args=(double *) RelinquishMagickMemory(args); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'g': { if (LocaleCompare(\"gamma\",option+1) == 0) { double constant; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); constant=StringToDouble(arg1,(char **) NULL); #if 0 \/* Using Gamma, via a cache *\/ if (IfPlusOp) constant=PerceptibleReciprocal(constant); (void) GammaImage(_image,constant,_exception); #else \/* Using Evaluate POW, direct update of values - more accurite *\/ if (IfNormalOp) constant=PerceptibleReciprocal(constant); (void) EvaluateImage(_image,PowEvaluateOperator,constant,_exception); _image->gamma*=StringToDouble(arg1,(char **) NULL); #endif \/* Set gamma setting -- Old meaning of \"+gamma\" * _image->gamma=StringToDouble(arg1,(char **) NULL); *\/ break; } if (LocaleCompare(\"gaussian-blur\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; new_image=GaussianBlurImage(_image,geometry_info.rho, geometry_info.sigma,_exception); break; } if (LocaleCompare(\"gaussian\",option+1) == 0) { CLIWandWarnReplaced(\"-gaussian-blur\"); (void) CLISimpleOperatorImage(cli_wand,\"-gaussian-blur\",arg1,NULL,exception); } if (LocaleCompare(\"geometry\",option+1) == 0) { \/* Record Image offset for composition. (A Setting) Resize last _image. (ListOperator) -- DEPRECIATE FUTURE: Why if no 'offset' does this resize ALL images? Also why is the setting recorded in the IMAGE non-sense! *\/ if (IfPlusOp) { \/* remove the previous composition geometry offset! *\/ if (_image->geometry != (char *) NULL) _image->geometry=DestroyString(_image->geometry); break; } if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParseRegionGeometry(_image,arg1,&geometry,_exception); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) (void) CloneString(&_image->geometry,arg1); else new_image=ResizeImage(_image,geometry.width,geometry.height, _image->filter,_exception); break; } if (LocaleCompare(\"grayscale\",option+1) == 0) { parse=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,\"UnrecognizedIntensityMethod\", option,arg1); (void) GrayscaleImage(_image,(PixelIntensityMethod) parse,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'h': { if (LocaleCompare(\"hough-lines\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if ((flags & XiValue) == 0) geometry_info.xi=40; new_image=HoughLineImage(_image,(size_t) geometry_info.rho, (size_t) geometry_info.sigma,(size_t) geometry_info.xi,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'i': { if (LocaleCompare(\"identify\",option+1) == 0) { const char *format, *text; format=GetImageOption(_image_info,\"format\"); if (format == (char *) NULL) { (void) IdentifyImage(_image,stdout,_image_info->verbose, _exception); break; } text=InterpretImageProperties(_image_info,_image,format,_exception); if (text == (char *) NULL) CLIWandExceptionBreak(OptionWarning,\"InterpretPropertyFailure\", option); (void) fputs(text,stdout); text=DestroyString((char *)text); break; } if (LocaleCompare(\"implode\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=ImplodeImage(_image,geometry_info.rho,_image->interpolate, _exception); break; } if (LocaleCompare(\"interpolative-resize\",option+1) == 0) { \/* FUTURE: New to IMv7 Roll into a resize special operator *\/ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParseRegionGeometry(_image,arg1,&geometry,_exception); new_image=InterpolativeResizeImage(_image,geometry.width, geometry.height,_image->interpolate,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'k': { if (LocaleCompare(\"kuwahara\",option+1) == 0) { \/* Edge preserving blur. *\/ flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho-0.5; new_image=KuwaharaImage(_image,geometry_info.rho,geometry_info.sigma, _exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'l': { if (LocaleCompare(\"lat\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & PercentValue) != 0) geometry_info.xi=(double) QuantumRange*geometry_info.xi\/100.0; new_image=AdaptiveThresholdImage(_image,(size_t) geometry_info.rho, (size_t) geometry_info.sigma,(double) geometry_info.xi, _exception); break; } if (LocaleCompare(\"level\",option+1) == 0) { double black_point, gamma, white_point; MagickStatusType flags; flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); black_point=geometry_info.rho; white_point=(double) QuantumRange; if ((flags & SigmaValue) != 0) white_point=geometry_info.sigma; gamma=1.0; if ((flags & XiValue) != 0) gamma=geometry_info.xi; if ((flags & PercentValue) != 0) { black_point*=(double) (QuantumRange\/100.0); white_point*=(double) (QuantumRange\/100.0); } if ((flags & SigmaValue) == 0) white_point=(double) QuantumRange-black_point; if (IfPlusOp || ((flags & AspectValue) != 0)) (void) LevelizeImage(_image,black_point,white_point,gamma,_exception); else (void) LevelImage(_image,black_point,white_point,gamma,_exception); break; } if (LocaleCompare(\"level-colors\",option+1) == 0) { char token[MagickPathExtent]; const char *p; PixelInfo black_point, white_point; p=(const char *) arg1; GetNextToken(p,&p,MagickPathExtent,token); \/* get black point color *\/ if ((isalpha((int) *token) != 0) || ((*token == '#') != 0)) (void) QueryColorCompliance(token,AllCompliance, &black_point,_exception); else (void) QueryColorCompliance(\"#000000\",AllCompliance, &black_point,_exception); if (isalpha((int) token[0]) || (token[0] == '#')) GetNextToken(p,&p,MagickPathExtent,token); if (*token == '\\0') white_point=black_point; \/* set everything to that color *\/ else { if ((isalpha((int) *token) == 0) && ((*token == '#') == 0)) GetNextToken(p,&p,MagickPathExtent,token); \/* Get white point color. *\/ if ((isalpha((int) *token) != 0) || ((*token == '#') != 0)) (void) QueryColorCompliance(token,AllCompliance, &white_point,_exception); else (void) QueryColorCompliance(\"#ffffff\",AllCompliance, &white_point,_exception); } (void) LevelImageColors(_image,&black_point,&white_point, IsPlusOp,_exception); break; } if (LocaleCompare(\"linear-stretch\",option+1) == 0) { double black_point, white_point; MagickStatusType flags; flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); black_point=geometry_info.rho; white_point=(double) _image->columns*_image->rows; if ((flags & SigmaValue) != 0) white_point=geometry_info.sigma; if ((flags & PercentValue) != 0) { black_point*=(double) _image->columns*_image->rows\/100.0; white_point*=(double) _image->columns*_image->rows\/100.0; } if ((flags & SigmaValue) == 0) white_point=(double) _image->columns*_image->rows- black_point; (void) LinearStretchImage(_image,black_point,white_point,_exception); break; } if (LocaleCompare(\"liquid-rescale\",option+1) == 0) { \/* FUTURE: Roll into a resize special operator *\/ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParseRegionGeometry(_image,arg1,&geometry,_exception); if ((flags & XValue) == 0) geometry.x=1; if ((flags & YValue) == 0) geometry.y=0; new_image=LiquidRescaleImage(_image,geometry.width, geometry.height,1.0*geometry.x,1.0*geometry.y,_exception); break; } if (LocaleCompare(\"local-contrast\",option+1) == 0) { MagickStatusType flags; flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) geometry_info.rho=10; if ((flags & SigmaValue) == 0) geometry_info.sigma=12.5; new_image=LocalContrastImage(_image,geometry_info.rho, geometry_info.sigma,exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'm': { if (LocaleCompare(\"magnify\",option+1) == 0) { new_image=MagnifyImage(_image,_exception); break; } if (LocaleCompare(\"map\",option+1) == 0) { CLIWandWarnReplaced(\"-remap\"); (void) CLISimpleOperatorImage(cli_wand,\"-remap\",NULL,NULL,exception); break; } if (LocaleCompare(\"mask\",option+1) == 0) { Image *mask; if (IfPlusOp) { \/* Remove a mask. *\/ (void) SetImageMask(_image,WritePixelMask,(Image *) NULL, _exception); break; } \/* Set the image mask. *\/ mask=GetImageCache(_image_info,arg1,_exception); if (mask == (Image *) NULL) break; (void) SetImageMask(_image,WritePixelMask,mask,_exception); mask=DestroyImage(mask); break; } if (LocaleCompare(\"matte\",option+1) == 0) { CLIWandWarnReplaced(IfNormalOp?\"-alpha Set\":\"-alpha Off\"); (void) SetImageAlphaChannel(_image,IfNormalOp ? SetAlphaChannel : DeactivateAlphaChannel, _exception); break; } if (LocaleCompare(\"mean-shift\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=0.10*QuantumRange; if ((flags & PercentValue) != 0) geometry_info.xi=(double) QuantumRange*geometry_info.xi\/100.0; new_image=MeanShiftImage(_image,(size_t) geometry_info.rho, (size_t) geometry_info.sigma,geometry_info.xi,_exception); break; } if (LocaleCompare(\"median\",option+1) == 0) { CLIWandWarnReplaced(\"-statistic Median\"); (void) CLISimpleOperatorImage(cli_wand,\"-statistic\",\"Median\",arg1,exception); break; } if (LocaleCompare(\"mode\",option+1) == 0) { \/* FUTURE: note this is also a special \"montage\" option *\/ CLIWandWarnReplaced(\"-statistic Mode\"); (void) CLISimpleOperatorImage(cli_wand,\"-statistic\",\"Mode\",arg1,exception); break; } if (LocaleCompare(\"modulate\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ModulateImage(_image,arg1,_exception); break; } if (LocaleCompare(\"monitor\",option+1) == 0) { (void) SetImageProgressMonitor(_image, IfNormalOp ? MonitorProgress : (MagickProgressMonitor) NULL,(void *) NULL); break; } if (LocaleCompare(\"monochrome\",option+1) == 0) { (void) SetImageType(_image,BilevelType,_exception); break; } if (LocaleCompare(\"morphology\",option+1) == 0) { char token[MagickPathExtent]; const char *p; KernelInfo *kernel; ssize_t iterations; p=arg1; GetNextToken(p,&p,MagickPathExtent,token); parse=ParseCommandOption(MagickMorphologyOptions,MagickFalse,token); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedFunction\",option, arg1); iterations=1L; GetNextToken(p,&p,MagickPathExtent,token); if ((*p == ':') || (*p == ',')) GetNextToken(p,&p,MagickPathExtent,token); if ((*p != '\\0')) iterations=(ssize_t) StringToLong(p); kernel=AcquireKernelInfo(arg2,exception); if (kernel == (KernelInfo *) NULL) CLIWandExceptArgBreak(OptionError,\"UnabletoParseKernel\",option,arg2); new_image=MorphologyImage(_image,(MorphologyMethod)parse,iterations, kernel,_exception); kernel=DestroyKernelInfo(kernel); break; } if (LocaleCompare(\"motion-blur\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; new_image=MotionBlurImage(_image,geometry_info.rho,geometry_info.sigma, geometry_info.xi,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'n': { if (LocaleCompare(\"negate\",option+1) == 0) { (void) NegateImage(_image, IsPlusOp, _exception); break; } if (LocaleCompare(\"noise\",option+1) == 0) { double attenuate; const char* value; if (IfNormalOp) { CLIWandWarnReplaced(\"-statistic NonPeak\"); (void) CLISimpleOperatorImage(cli_wand,\"-statistic\",\"NonPeak\",arg1,exception); break; } parse=ParseCommandOption(MagickNoiseOptions,MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedNoiseType\", option,arg1); attenuate=1.0; value=GetImageOption(_image_info,\"attenuate\"); if (value != (const char *) NULL) attenuate=StringToDouble(value,(char **) NULL); new_image=AddNoiseImage(_image,(NoiseType)parse,attenuate, _exception); break; } if (LocaleCompare(\"normalize\",option+1) == 0) { (void) NormalizeImage(_image,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'o': { if (LocaleCompare(\"opaque\",option+1) == 0) { PixelInfo target; (void) QueryColorCompliance(arg1,AllCompliance,&target,_exception); (void) OpaquePaintImage(_image,&target,&_draw_info->fill,IsPlusOp, _exception); break; } if (LocaleCompare(\"ordered-dither\",option+1) == 0) { (void) OrderedDitherImage(_image,arg1,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'p': { if (LocaleCompare(\"paint\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=OilPaintImage(_image,geometry_info.rho,geometry_info.sigma, _exception); break; } if (LocaleCompare(\"perceptible\",option+1) == 0) { (void) PerceptibleImage(_image,StringToDouble(arg1,(char **) NULL), _exception); break; } if (LocaleCompare(\"polaroid\",option+1) == 0) { const char *caption; double angle; if (IfPlusOp) { RandomInfo *random_info; random_info=AcquireRandomInfo(); angle=22.5*(GetPseudoRandomValue(random_info)-0.5); random_info=DestroyRandomInfo(random_info); } else { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); angle=geometry_info.rho; } caption=GetImageProperty(_image,\"caption\",_exception); new_image=PolaroidImage(_image,_draw_info,caption,angle, _image->interpolate,_exception); break; } if (LocaleCompare(\"posterize\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) PosterizeImage(_image,(size_t) geometry_info.rho, _quantize_info->dither_method,_exception); break; } if (LocaleCompare(\"preview\",option+1) == 0) { \/* FUTURE: should be a 'Genesis' option? Option however is also in WandSettingOptionInfo() Why??? *\/ parse=ParseCommandOption(MagickPreviewOptions, MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedPreviewType\", option,arg1); new_image=PreviewImage(_image,(PreviewType)parse,_exception); break; } if (LocaleCompare(\"profile\",option+1) == 0) { const char *name; const StringInfo *profile; Image *profile_image; ImageInfo *profile_info; \/* Note: arguments do not have percent escapes expanded *\/ if (IfPlusOp) { \/* Remove a profile from the _image. *\/ (void) ProfileImage(_image,arg1,(const unsigned char *) NULL,0,_exception); break; } \/* Associate a profile with the _image. *\/ profile_info=CloneImageInfo(_image_info); profile=GetImageProfile(_image,\"iptc\"); if (profile != (StringInfo *) NULL) profile_info->profile=(void *) CloneStringInfo(profile); profile_image=GetImageCache(profile_info,arg1,_exception); profile_info=DestroyImageInfo(profile_info); if (profile_image == (Image *) NULL) { StringInfo *profile; profile_info=CloneImageInfo(_image_info); (void) CopyMagickString(profile_info->filename,arg1, MagickPathExtent); profile=FileToStringInfo(profile_info->filename,~0UL,_exception); if (profile != (StringInfo *) NULL) { (void) SetImageInfo(profile_info,0,_exception); (void) ProfileImage(_image,profile_info->magick, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),_exception); profile=DestroyStringInfo(profile); } profile_info=DestroyImageInfo(profile_info); break; } ResetImageProfileIterator(profile_image); name=GetNextImageProfile(profile_image); while (name != (const char *) NULL) { profile=GetImageProfile(profile_image,name); if (profile != (StringInfo *) NULL) (void) ProfileImage(_image,name,GetStringInfoDatum(profile), (size_t) GetStringInfoLength(profile),_exception); name=GetNextImageProfile(profile_image); } profile_image=DestroyImage(profile_image); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'r': { if (LocaleCompare(\"raise\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParsePageGeometry(_image,arg1,&geometry,_exception); (void) RaiseImage(_image,&geometry,IsNormalOp,_exception); break; } if (LocaleCompare(\"random-threshold\",option+1) == 0) { double min_threshold, max_threshold; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); min_threshold=0.0; max_threshold=(double) QuantumRange; flags=ParseGeometry(arg1,&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(arg1,'%') != (char *) NULL) { max_threshold*=(double) (0.01*QuantumRange); min_threshold*=(double) (0.01*QuantumRange); } (void) RandomThresholdImage(_image,min_threshold,max_threshold, _exception); break; } if (LocaleCompare(\"range-threshold\",option+1) == 0) { \/* Range threshold image. *\/ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParseGeometry(arg1,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if ((flags & XiValue) == 0) geometry_info.xi=geometry_info.sigma; if ((flags & PsiValue) == 0) geometry_info.psi=geometry_info.xi; if (strchr(arg1,'%') != (char *) NULL) { geometry_info.rho*=(double) (0.01*QuantumRange); geometry_info.sigma*=(double) (0.01*QuantumRange); geometry_info.xi*=(double) (0.01*QuantumRange); geometry_info.psi*=(double) (0.01*QuantumRange); } (void) RangeThresholdImage(_image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,geometry_info.psi,exception); break; } if (LocaleCompare(\"read-mask\",option+1) == 0) { \/* Note: arguments do not have percent escapes expanded *\/ Image *mask; if (IfPlusOp) { \/* Remove a mask. *\/ (void) SetImageMask(_image,ReadPixelMask,(Image *) NULL, _exception); break; } \/* Set the image mask. *\/ mask=GetImageCache(_image_info,arg1,_exception); if (mask == (Image *) NULL) break; (void) SetImageMask(_image,ReadPixelMask,mask,_exception); mask=DestroyImage(mask); break; } if (LocaleCompare(\"recolor\",option+1) == 0) { CLIWandWarnReplaced(\"-color-matrix\"); (void) CLISimpleOperatorImage(cli_wand,\"-color-matrix\",arg1,NULL, exception); } if (LocaleCompare(\"region\",option+1) == 0) { if (*option == '+') { (void) SetImageRegionMask(_image,WritePixelMask, (const RectangleInfo *) NULL,_exception); break; } if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParseGravityGeometry(_image,arg1,&geometry,_exception); (void) SetImageRegionMask(_image,WritePixelMask,&geometry,_exception); break; } if (LocaleCompare(\"remap\",option+1) == 0) { \/* Note: arguments do not have percent escapes expanded *\/ Image *remap_image; remap_image=GetImageCache(_image_info,arg1,_exception); if (remap_image == (Image *) NULL) break; (void) RemapImage(_quantize_info,_image,remap_image,_exception); remap_image=DestroyImage(remap_image); break; } if (LocaleCompare(\"repage\",option+1) == 0) { if (IfNormalOp) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option, arg1); (void) ResetImagePage(_image,arg1); } else (void) ParseAbsoluteGeometry(\"0x0+0+0\",&_image->page); break; } if (LocaleCompare(\"resample\",option+1) == 0) { \/* FUTURE: Roll into a resize special operation *\/ flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; new_image=ResampleImage(_image,geometry_info.rho, geometry_info.sigma,_image->filter,_exception); break; } if (LocaleCompare(\"resize\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParseRegionGeometry(_image,arg1,&geometry,_exception); new_image=ResizeImage(_image,geometry.width,geometry.height, _image->filter,_exception); break; } if (LocaleCompare(\"roll\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParsePageGeometry(_image,arg1,&geometry,_exception); if ((flags & PercentValue) != 0) { geometry.x*=(double) _image->columns\/100.0; geometry.y*=(double) _image->rows\/100.0; } new_image=RollImage(_image,geometry.x,geometry.y,_exception); break; } if (LocaleCompare(\"rotate\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & GreaterValue) != 0 && (_image->columns <= _image->rows)) break; if ((flags & LessValue) != 0 && (_image->columns >= _image->rows)) break; new_image=RotateImage(_image,geometry_info.rho,_exception); break; } if (LocaleCompare(\"rotational-blur\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=RotationalBlurImage(_image,geometry_info.rho,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 's': { if (LocaleCompare(\"sample\",option+1) == 0) { \/* FUTURE: Roll into a resize special operator *\/ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParseRegionGeometry(_image,arg1,&geometry,_exception); new_image=SampleImage(_image,geometry.width,geometry.height, _exception); break; } if (LocaleCompare(\"scale\",option+1) == 0) { \/* FUTURE: Roll into a resize special operator *\/ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParseRegionGeometry(_image,arg1,&geometry,_exception); new_image=ScaleImage(_image,geometry.width,geometry.height, _exception); break; } if (LocaleCompare(\"segment\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; (void) SegmentImage(_image,_image->colorspace, _image_info->verbose,geometry_info.rho,geometry_info.sigma, _exception); break; } if (LocaleCompare(\"selective-blur\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & PercentValue) != 0) geometry_info.xi=(double) QuantumRange*geometry_info.xi\/100.0; new_image=SelectiveBlurImage(_image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,_exception); break; } if (LocaleCompare(\"separate\",option+1) == 0) { \/* WARNING: This can generate multiple images! *\/ \/* FUTURE - this may be replaced by a \"-channel\" method *\/ new_image=SeparateImages(_image,_exception); break; } if (LocaleCompare(\"sepia-tone\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=SepiaToneImage(_image,StringToDoubleInterval(arg1, (double) QuantumRange+1.0),_exception); break; } if (LocaleCompare(\"shade\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if (((flags & RhoValue) == 0) || ((flags & SigmaValue) == 0)) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=ShadeImage(_image,IsNormalOp,geometry_info.rho, geometry_info.sigma,_exception); break; } if (LocaleCompare(\"shadow\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=4.0; if ((flags & PsiValue) == 0) geometry_info.psi=4.0; new_image=ShadowImage(_image,geometry_info.rho,geometry_info.sigma, (ssize_t) ceil(geometry_info.xi-0.5),(ssize_t) ceil(geometry_info.psi-0.5),_exception); break; } if (LocaleCompare(\"sharpen\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=0.0; new_image=SharpenImage(_image,geometry_info.rho,geometry_info.sigma, _exception); break; } if (LocaleCompare(\"shave\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParsePageGeometry(_image,arg1,&geometry,_exception); new_image=ShaveImage(_image,&geometry,_exception); break; } if (LocaleCompare(\"shear\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; new_image=ShearImage(_image,geometry_info.rho,geometry_info.sigma, _exception); break; } if (LocaleCompare(\"sigmoidal-contrast\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=(double) QuantumRange\/2.0; if ((flags & PercentValue) != 0) geometry_info.sigma=(double) QuantumRange*geometry_info.sigma\/ 100.0; (void) SigmoidalContrastImage(_image,IsNormalOp,geometry_info.rho, geometry_info.sigma,_exception); break; } if (LocaleCompare(\"sketch\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; new_image=SketchImage(_image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,_exception); break; } if (LocaleCompare(\"solarize\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) SolarizeImage(_image,StringToDoubleInterval(arg1,(double) QuantumRange+1.0),_exception); break; } if (LocaleCompare(\"sparse-color\",option+1) == 0) { parse= ParseCommandOption(MagickSparseColorOptions,MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedSparseColorMethod\", option,arg1); new_image=SparseColorOption(_image,(SparseColorMethod)parse,arg2, _exception); break; } if (LocaleCompare(\"splice\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); flags=ParseGravityGeometry(_image,arg1,&geometry,_exception); new_image=SpliceImage(_image,&geometry,_exception); break; } if (LocaleCompare(\"spread\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg2); new_image=SpreadImage(_image,_image->interpolate,geometry_info.rho, _exception); break; } if (LocaleCompare(\"statistic\",option+1) == 0) { parse=ParseCommandOption(MagickStatisticOptions,MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedStatisticType\", option,arg1); flags=ParseGeometry(arg2,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg2); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; new_image=StatisticImage(_image,(StatisticType)parse, (size_t) geometry_info.rho,(size_t) geometry_info.sigma, _exception); break; } if (LocaleCompare(\"strip\",option+1) == 0) { (void) StripImage(_image,_exception); break; } if (LocaleCompare(\"swirl\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=SwirlImage(_image,geometry_info.rho, _image->interpolate,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 't': { if (LocaleCompare(\"threshold\",option+1) == 0) { double threshold; threshold=(double) QuantumRange\/2; if (IfNormalOp) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); threshold=StringToDoubleInterval(arg1,(double) QuantumRange+1.0); } (void) BilevelImage(_image,threshold,_exception); break; } if (LocaleCompare(\"thumbnail\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParseRegionGeometry(_image,arg1,&geometry,_exception); new_image=ThumbnailImage(_image,geometry.width,geometry.height, _exception); break; } if (LocaleCompare(\"tint\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); new_image=TintImage(_image,arg1,&_draw_info->fill,_exception); break; } if (LocaleCompare(\"transform\",option+1) == 0) { CLIWandWarnReplaced(\"+distort AffineProjection\"); new_image=AffineTransformImage(_image,&_draw_info->affine,_exception); break; } if (LocaleCompare(\"transparent\",option+1) == 0) { PixelInfo target; (void) QueryColorCompliance(arg1,AllCompliance,&target,_exception); (void) TransparentPaintImage(_image,&target,(Quantum) TransparentAlpha,IsPlusOp,_exception); break; } if (LocaleCompare(\"transpose\",option+1) == 0) { new_image=TransposeImage(_image,_exception); break; } if (LocaleCompare(\"transverse\",option+1) == 0) { new_image=TransverseImage(_image,_exception); break; } if (LocaleCompare(\"trim\",option+1) == 0) { new_image=TrimImage(_image,_exception); break; } if (LocaleCompare(\"type\",option+1) == 0) { \/* Note that \"type\" setting should have already been defined *\/ (void) SetImageType(_image,_image_info->type,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'u': { if (LocaleCompare(\"unique\",option+1) == 0) { \/* FUTURE: move to SyncImageSettings() and AcqireImage()??? Option is not documented, bt appears to be for \"identify\". We may need a identify specific verbose! *\/ if (IsPlusOp) { (void) DeleteImageArtifact(_image,\"identify:unique-colors\"); break; } (void) SetImageArtifact(_image,\"identify:unique-colors\",\"true\"); (void) SetImageArtifact(_image,\"verbose\",\"true\"); break; } if (LocaleCompare(\"unique-colors\",option+1) == 0) { new_image=UniqueImageColors(_image,_exception); break; } if (LocaleCompare(\"unsharp\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=1.0; if ((flags & PsiValue) == 0) geometry_info.psi=0.05; new_image=UnsharpMaskImage(_image,geometry_info.rho, geometry_info.sigma,geometry_info.xi,geometry_info.psi,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'v': { if (LocaleCompare(\"verbose\",option+1) == 0) { \/* FUTURE: move to SyncImageSettings() and AcquireImage()??? three places! ImageArtifact ImageOption _image_info->verbose Some how new images also get this artifact! *\/ (void) SetImageArtifact(_image,option+1, IfNormalOp ? \"true\" : \"false\" ); break; } if (LocaleCompare(\"vignette\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; if ((flags & XiValue) == 0) geometry_info.xi=0.1*_image->columns; if ((flags & PsiValue) == 0) geometry_info.psi=0.1*_image->rows; if ((flags & PercentValue) != 0) { geometry_info.xi*=(double) _image->columns\/100.0; geometry_info.psi*=(double) _image->rows\/100.0; } new_image=VignetteImage(_image,geometry_info.rho,geometry_info.sigma, (ssize_t) ceil(geometry_info.xi-0.5),(ssize_t) ceil(geometry_info.psi-0.5),_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'w': { if (LocaleCompare(\"wave\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & (RhoValue|SigmaValue)) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; new_image=WaveImage(_image,geometry_info.rho,geometry_info.sigma, _image->interpolate,_exception); break; } if (LocaleCompare(\"wavelet-denoise\",option+1) == 0) { flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if ((flags & PercentValue) != 0) { geometry_info.rho=QuantumRange*geometry_info.rho\/100.0; geometry_info.sigma=QuantumRange*geometry_info.sigma\/100.0; } if ((flags & SigmaValue) == 0) geometry_info.sigma=0.0; new_image=WaveletDenoiseImage(_image,geometry_info.rho, geometry_info.sigma,_exception); break; } if (LocaleCompare(\"white-threshold\",option+1) == 0) { if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) WhiteThresholdImage(_image,arg1,_exception); break; } if (LocaleCompare(\"write-mask\",option+1) == 0) { \/* Note: arguments do not have percent escapes expanded *\/ Image *mask; if (IfPlusOp) { \/* Remove a mask. *\/ (void) SetImageMask(_image,WritePixelMask,(Image *) NULL, _exception); break; } \/* Set the image mask. *\/ mask=GetImageCache(_image_info,arg1,_exception); if (mask == (Image *) NULL) break; (void) SetImageMask(_image,WritePixelMask,mask,_exception); mask=DestroyImage(mask); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } default: CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } \/* clean up percent escape interpreted strings *\/ if (arg1 != arg1n ) arg1=DestroyString((char *)arg1); if (arg2 != arg2n ) arg2=DestroyString((char *)arg2); \/* Replace current image with any image that was generated and set image point to last image (so image->next is correct) *\/ if (new_image != (Image *) NULL) ReplaceImageInListReturnLast(&_image,new_image); return(MagickTrue); #undef _image_info #undef _draw_info #undef _quantize_info #undef _image #undef _exception #undef IfNormalOp #undef IfPlusOp #undef IsNormalOp #undef IsPlusOp }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":367981,"input":"int LibRaw::parse_tiff_ifd(int base) { unsigned entries, tag, type, len, plen = 16, save; int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1}; unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095}; unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0; struct jhead jh; ushort *rafdata; if (tiff_nifds >= sizeof tiff_ifd \/ sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; INT64 fsize = ifp->size(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); \/\/ Recover tiff-read position!! continue; } if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | (is_pana_raw ? 0x30000 : ((ifd + 1) << 20)), type, len, order, ifp, base); fseek(ifp, savepos, SEEK_SET); } if (!is_pana_raw) { \/* processing of EXIF tags that collide w\/ PanasonicRaw tags *\/ switch (tag) { case 0x0001: if (len == 4) is_pana_raw = get4(); break; case 0x000b: \/* 11, Std. EXIF Software tag *\/ fgets(software, 64, ifp); if (!strncmp(software, \"Adobe\", 5) || !strncmp(software, \"dcraw\", 5) || !strncmp(software, \"UFRaw\", 5) || !strncmp(software, \"Bibble\", 6) || !strcmp(software, \"Digital Photo Professional\")) is_raw = 0; break; case 0x001c: \/* 28, safeguard, probably not needed *\/ case 0x001d: \/* 29, safeguard, probably not needed *\/ case 0x001e: \/* 30, safeguard, probably not needed *\/ cblack[tag - 0x001c] = get2(); cblack[3] = cblack[1]; break; case 0x0111: \/* 273, StripOffset *\/ if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); \/\/ restore position } \/* fallback *\/ case 0x0201: \/* 513, JpegIFOffset *\/ case 0xf007: \/\/ 61447 tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width \/= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; } } else { \/* processing Panasonic-specific \"PanasonicRaw\" tags *\/ switch (tag) { case 0x0004: \/* 4, SensorTopBorder *\/ imgdata.sizes.raw_inset_crop.ctop = get2(); break; case 0x000a: \/* 10, BitsPerSample *\/ pana_bpp = get2(); break; case 0x000b: \/* 11, Compression *\/ imPana.Compression = get2(); break; case 0x000e: \/* 14, LinearityLimitRed *\/ case 0x000f: \/* 15, LinearityLimitGreen *\/ case 0x0010: \/* 16, LinearityLimitBlue *\/ imgdata.color.linear_max[tag - 14] = get2(); if (tag == 0x000f) \/\/ 15, LinearityLimitGreen imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; case 0x0013: \/* 19, WBInfo *\/ if ((i = get2()) > 0x100) break; for (c = 0; c < i; c++) { if ((j = get2()) < 0x100) { imgdata.color.WB_Coeffs[j][0] = get2(); imgdata.color.WB_Coeffs[j][2] = get2(); imgdata.color.WB_Coeffs[j][1] = imgdata.color.WB_Coeffs[j][3] = 0x100; } else \/\/ light source out of EXIF numbers range get4(); } break; case 0x0018: \/* 24, HighISOMultiplierRed *\/ case 0x0019: \/* 25, HighISOMultiplierGreen *\/ case 0x001a: \/* 26, HighISOMultiplierBlue *\/ imPana.HighISOMultiplier[tag - 0x0018] = get2(); break; case 0x001c: \/* 28, BlackLevelRed *\/ case 0x001d: \/* 29, BlackLevelGreen *\/ case 0x001e: \/* 30, BlackLevelBlue *\/ pana_black[tag - 0x001c] = get2(); break; case 0x002d: \/* 45, RawFormat *\/ \/* pana_encoding: tag 0x002d (45dec) not used - DMC-LX1\/FZ30\/FZ50\/L1\/LX1\/LX2 2 - RAW DMC-FZ8\/FZ18 3 - RAW DMC-L10 4 - RW2 for most other models, including G9 in \"pixel shift off\" mode and YUNEEC CGO4 (must add 15 to black levels for RawFormat == 4) 5 - RW2 DC-GH5s; G9 in \"pixel shift on\" mode 6 - RW2 DC-S1, DC-S1R in \"pixel shift off\" mode 7 - RW2 DC-S1R (probably DC-S1 too) in \"pixel shift on\" mode *\/ pana_encoding = get2(); break; case 0x002f: \/* 47, CropTop *\/ imgdata.sizes.raw_inset_crop.ctop = get2(); break; case 0x0030: \/* 48, CropLeft *\/ imgdata.sizes.raw_inset_crop.cleft = get2(); break; case 0x0031: \/* 49, CropBottom *\/ imgdata.sizes.raw_inset_crop.cheight = get2() - imgdata.sizes.raw_inset_crop.ctop; break; case 0x0032: \/* 50, CropRight *\/ imgdata.sizes.raw_inset_crop.cwidth = get2() - imgdata.sizes.raw_inset_crop.cleft; break; case 0x0037: \/* 55, ISO if ISO in 0x8827 & ISO in 0x0017 == 65535 *\/ if (iso_speed == 65535) iso_speed = get4(); break; case 0x011c: \/* 284, Gamma *\/ { int n = get2(); if (n >= 1024) imPana.gamma = (float)n \/ 1024.0f; else if (n >= 256) imPana.gamma = (float)n \/ 256.0f; else imPana.gamma = (float)n \/ 100.0f; } break; case 0x0120: \/* 288, CameraIFD, contains tags 0x1xxx, 0x2xxx, 0x3xxx *\/ { unsigned sorder = order; unsigned long sbase = base; base = ftell(ifp); order = get2(); fseek(ifp, 2, SEEK_CUR); fseek(ifp, get4() - 8, SEEK_CUR); parse_tiff_ifd(base); base = sbase; order = sorder; } break; case 0x0121: \/* 289, Multishot, 0 is Off, 65536 is Pixel Shift *\/ imPana.Multishot = get4(); break; case 0x1203: \/* 4611, FocalLengthIn35mmFormat, contained in 0x0120 CameraIFD *\/ if (imgdata.lens.FocalLengthIn35mmFormat < 0.65f) imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0x2009: \/* 8201, contained in 0x0120 CameraIFD *\/ if ((pana_encoding == 4) || (pana_encoding == 5)) { i = MIN(8, len); int permut[8] = {3, 2, 1, 0, 3 + 4, 2 + 4, 1 + 4, 0 + 4}; imPana.BlackLevelDim = len; for (j = 0; j < i; j++) { imPana.BlackLevel[permut[j]] = (float)(get2()) \/ (float)(powf(2.f, 14.f - pana_bpp)); } } break; case 0x3420: \/* 13344, WB_RedLevelAuto, contained in 0x0120 CameraIFD *\/ imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = 1024.0f; break; case 0x3421: \/* 13345, WB_BlueLevelAuto, contained in 0x0120 CameraIFD *\/ imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); break; case 0x0002: \/* 2, ImageWidth *\/ tiff_ifd[ifd].t_width = getint(type); break; case 0x0003: \/* 3, ImageHeight *\/ tiff_ifd[ifd].t_height = getint(type); break; case 0x0005: \/* 5, SensorLeftBorder *\/ width = get2(); imgdata.sizes.raw_inset_crop.cleft = width; break; case 0x0006: \/* 6, SensorBottomBorder *\/ height = get2(); imgdata.sizes.raw_inset_crop.cheight = height - imgdata.sizes.raw_inset_crop.ctop; break; case 0x0007: \/* 7, SensorRightBorder *\/ i = get2(); width += i; imgdata.sizes.raw_inset_crop.cwidth = i - imgdata.sizes.raw_inset_crop.cleft; break; case 0x0009: \/* 9, CFAPattern *\/ if ((i = get2())) filters = i; break; case 0x0011: \/* 17, RedBalance *\/ case 0x0012: \/* 18, BlueBalance *\/ if (type == 3 && len == 1) cam_mul[(tag - 0x0011) * 2] = get2() \/ 256.0; break; case 0x0017: \/* 23, ISO *\/ if (type == 3) iso_speed = get2(); break; case 0x0024: \/* 36, WBRedLevel *\/ case 0x0025: \/* 37, WBGreenLevel *\/ case 0x0026: \/* 38, WBBlueLevel *\/ cam_mul[tag - 0x0024] = get2(); break; case 0x0027: \/* 39, WBInfo2 *\/ if ((i = get2()) > 0x100) break; for (c = 0; c < i; c++) { if ((j = get2()) < 0x100) { imgdata.color.WB_Coeffs[j][0] = get2(); imgdata.color.WB_Coeffs[j][1] = imgdata.color.WB_Coeffs[j][3] = get2(); imgdata.color.WB_Coeffs[j][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } break; if (len < 50 || cam_mul[0] > 0.001f) break; fseek(ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 0x002e: \/* 46, JpgFromRaw *\/ if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 0x0118: \/* 280, Panasonic RW2 offset *\/ if (type != 4) break; load_raw = &LibRaw::panasonic_load_raw; load_flags = 0x2008; case 0x0111: \/* 273, StripOffset *\/ if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); \/\/ restore position } \/* fallthrough *\/ tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width \/= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; } } \/* processing of Panasonic-specific tags finished *\/ switch (tag) { \/* processing of general EXIF tags *\/ case 0xf000: \/* 61440, Fuji HS10 table *\/ fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; case 0x00fe: \/* NewSubfileType *\/ tiff_ifd[ifd].newsubfiletype = getreal(type); break; case 0x0100: \/* 256, ImageWidth *\/ case 0xf001: \/* 61441, Fuji RAF IFD 0xf001 RawImageFullWidth *\/ tiff_ifd[ifd].t_width = getint(type); break; case 0x0101: \/* 257, ImageHeight *\/ case 0xf002: \/* 61442, Fuji RAF IFD 0xf002 RawImageFullHeight *\/ tiff_ifd[ifd].t_height = getint(type); break; case 0x0102: \/* 258, BitsPerSample *\/ case 0xf003: \/* 61443, Fuji RAF IFD 0xf003 *\/ tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 0xf006: \/* 61446, Fuji RAF IFD 0xf006 *\/ raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &LibRaw::packed_load_raw; load_flags = get4() ? 24 : 80; break; case 0x0103: \/* 259, Compression *\/ \/* 262 = Kodak 262 32767 = Sony ARW Compressed 32769 = Packed RAW 32770 = Samsung SRW Compressed 32772 = Samsung SRW Compressed 2 32867 = Kodak KDC Compressed 34713 = Nikon NEF Compressed 65000 = Kodak DCR Compressed 65535 = Pentax PEF Compressed *\/ tiff_ifd[ifd].comp = getint(type); break; case 0x0106: \/* 262, PhotometricInterpretation *\/ tiff_ifd[ifd].phint = get2(); break; case 0x010e: \/* 270, ImageDescription *\/ fread(desc, 512, 1, ifp); break; case 0x010f: \/* 271, Make *\/ fgets(make, 64, ifp); break; case 0x0110: \/* 272, Model *\/ if (!strncmp(make, \"Hasselblad\", 10) && model[0] && (imHassy.format != LIBRAW_HF_Imacon)) break; fgets(model, 64, ifp); break; case 0x0116: \/\/ 278 tiff_ifd[ifd].rows_per_strip = getint(type); break; case 0x0112: \/* 274, Orientation *\/ tiff_ifd[ifd].t_flip = \"50132467\"[get2() & 7] - '0'; break; case 0x0115: \/* 277, SamplesPerPixel *\/ tiff_ifd[ifd].samples = getint(type) & 7; break; case 0x0117: \/* 279, StripByteCounts *\/ if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_byte_counts[i] = get4(); fseek(ifp, sav, SEEK_SET); \/\/ restore position } \/* fallback *\/ case 0x0202: \/\/ 514 case 0xf008: \/\/ 61448 tiff_ifd[ifd].bytes = get4(); break; case 0xf00e: \/\/ 61454, FujiFilm \"As Shot\" FORC3 cam_mul[(4 - c) % 3] = getint(type); break; case 0x0131: \/* 305, Software *\/ fgets(software, 64, ifp); if (!strncmp(software, \"Adobe\", 5) || !strncmp(software, \"dcraw\", 5) || !strncmp(software, \"UFRaw\", 5) || !strncmp(software, \"Bibble\", 6) || !strcmp(software, \"Digital Photo Professional\")) is_raw = 0; break; case 0x0132: \/* 306, DateTime *\/ get_timestamp(0); break; case 0x013b: \/* 315, Artist *\/ fread(artist, 64, 1, ifp); break; case 0x013d: \/\/ 317 tiff_ifd[ifd].predictor = getint(type); break; case 0x0142: \/* 322, TileWidth *\/ tiff_ifd[ifd].t_tile_width = getint(type); break; case 0x0143: \/* 323, TileLength *\/ tiff_ifd[ifd].t_tile_length = getint(type); break; case 0x0144: \/* 324, TileOffsets *\/ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &LibRaw::sinar_4shot_load_raw; is_raw = 5; } break; case 0x0145: \/\/ 325 tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4(); break; case 0x014a: \/* 330, SubIFDs *\/ if (!strcmp(model, \"DSLR-A100\") && tiff_ifd[ifd].t_width == 3872) { load_raw = &LibRaw::sony_arw_load_raw; data_offset = get4() + base; ifd++; if (ifd >= sizeof tiff_ifd \/ sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; break; } if (!strncmp(make, \"Hasselblad\", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek(ifp, ftell(ifp) + 4, SEEK_SET); fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; } if (len > 1000) len = 1000; \/* 1000 SubIFDs is enough *\/ while (len--) { i = ftell(ifp); fseek(ifp, get4() + base, SEEK_SET); if (parse_tiff_ifd(base)) break; fseek(ifp, i + 4, SEEK_SET); } break; case 0x0153: \/\/ 339 tiff_ifd[ifd].sample_format = getint(type); break; case 0x0190: \/\/ 400 strcpy(make, \"Sarnoff\"); maximum = 0xfff; break; case 0x02bc: \/\/ 700 if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char *)malloc(xmplen = len + 1); fread(xmpdata, len, 1, ifp); xmpdata[len] = 0; } break; case 0x7000: imSony.SonyRawFileType = get2(); break; case 0x7010: \/\/ 28688 FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff; for (i = 0; i < 5; i++) for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++) curve[j] = curve[j - 1] + (1 << i); break; case 0x7200: \/\/ 29184, Sony SR2Private sony_offset = get4(); break; case 0x7201: \/\/ 29185, Sony SR2Private sony_length = get4(); break; case 0x7221: \/\/ 29217, Sony SR2Private sony_key = get4(); break; case 0x7250: \/\/ 29264, Sony SR2Private parse_minolta(ftell(ifp)); raw_width = 0; break; case 0x7303: \/\/ 29443, Sony SR2SubIFD FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 0x7313: \/\/ 29459, Sony SR2SubIFD FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 0x7310: \/\/ 29456, Sony SR2SubIFD FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black = i; break; case 0x827d: \/* 33405, Model2 *\/ \/* for Kodak ProBack 645 PB645x-yyyy 'x' is: 'M' for Mamiya 645 'C' for Contax 645 'H' for Hasselblad H-series *\/ fgets(model2, 64, ifp); break; case 0x828d: \/* 33421, CFARepeatPatternDim *\/ if (get2() == 6 && get2() == 6) tiff_ifd[ifd].t_filters = filters = 9; break; case 0x828e: \/* 33422, CFAPattern *\/ if (filters == 9) { FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 0xfd09: \/* 64777, Kodak P-series *\/ if (len == 36) { tiff_ifd[ifd].t_filters = filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if (len > 0) { if ((plen = len) > 16) plen = 16; fread(cfa_pat, 1, plen, ifp); for (colors = cfa = i = 0; i < plen && colors < 4; i++) { if (cfa_pat[i] > 31) continue; \/\/ Skip wrong data colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy(cfa_pc, \"\\003\\004\\005\", 3); \/* CMY *\/ if (cfa == 072) memcpy(cfa_pc, \"\\005\\003\\004\\001\", 4); \/* GMCY *\/ goto guess_cfa_pc; } break; case 0x8290: \/\/ 33424 case 0xfe00: \/\/ 65024 fseek(ifp, get4() + base, SEEK_SET); parse_kodak_ifd(base); break; case 0x829a: \/* 33434, ExposureTime *\/ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 0x829d: \/* 33437, FNumber *\/ aperture = getreal(type); break; case 0x9400: imgdata.makernotes.common.exifAmbientTemperature = getreal(type); if ((imgdata.makernotes.common.CameraTemperature > -273.15f) && ((OlyID == 0x4434353933ULL) || (OlyID == 0x4434363033ULL))) \/\/ TG-5\/6 imgdata.makernotes.common.CameraTemperature += imgdata.makernotes.common.exifAmbientTemperature; break; case 0x9401: imgdata.makernotes.common.exifHumidity = getreal(type); break; case 0x9402: imgdata.makernotes.common.exifPressure = getreal(type); break; case 0x9403: imgdata.makernotes.common.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.makernotes.common.exifAcceleration = getreal(type); break; case 0x9405: imgdata.makernotes.common.exifCameraElevationAngle = getreal(type); break; case 0xa405: \/\/ FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: \/\/ BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: \/\/ LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: \/\/ LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: \/\/ DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa420: \/* 42016, ImageUniqueID *\/ stmread(imgdata.color.ImageUniqueID, len, ifp); break; case 0xc65d: \/* 50781, RawDataUniqueID *\/ imgdata.color.RawDataUniqueID[16] = 0; fread(imgdata.color.RawDataUniqueID, 1, 16, ifp); break; case 0xa433: \/\/ LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: \/\/ LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, \"----\", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) \/ 2.0f)); break; case 0x8602: \/* 34306, Leaf white balance *\/ FORC4 { int q = get2(); if (q) cam_mul[c ^ 1] = 4096.0 \/ q; } break; case 0x8603: \/* 34307, Leaf CatchLight color matrix *\/ fread(software, 1, 7, ifp); if (strncmp(software, \"MATRIX\", 6)) break; colors = 4; for (raw_color = i = 0; i < 3; i++) { FORC4 fscanf(ifp, \"%f\", &rgb_cam[i][c ^ 1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] \/= MAX(1, num); } break; case 0x8606: \/* 34310, Leaf metadata *\/ parse_mos(ftell(ifp)); case 0x85ff: \/\/ 34303 strcpy(make, \"Leaf\"); break; case 0x8769: \/* 34665, EXIF tag *\/ fseek(ifp, get4() + base, SEEK_SET); parse_exif(base); break; case 0x8825: \/* 34853, GPSInfo tag *\/ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); } break; case 0x8773: \/* 34675, InterColorProfile *\/ case 0xc68f: \/* 50831, AsShotICCProfile *\/ profile_offset = ftell(ifp); profile_length = len; break; case 0x9102: \/* 37122, CompressedBitsPerPixel *\/ kodak_cbpp = get4(); break; case 0x920a: \/* 37386, FocalLength *\/ focal_len = getreal(type); break; case 0x9211: \/* 37393, ImageNumber *\/ shot_order = getint(type); break; case 0x9215: \/* 37397, ExposureIndex *\/ imgdata.makernotes.common.exifExposureIndex = getreal(type); break; case 0x9218: \/* 37400, old Kodak KDC tag *\/ for (raw_color = i = 0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 0xa010: \/\/ 40976 strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 0x8002: \/\/ 32770 load_raw = &LibRaw::samsung_load_raw; break; case 0x8004: \/\/ 32772 load_raw = &LibRaw::samsung2_load_raw; break; case 0x8005: \/\/ 32773 load_raw = &LibRaw::samsung3_load_raw; break; } break; case 0xb4c3: \/* 46275, Imacon tags *\/ imHassy.format = LIBRAW_HF_Imacon; strcpy(make, \"Imacon\"); data_offset = ftell(ifp); ima_len = len; break; case 0xb4c7: \/\/ 46279 if (!ima_len) break; fseek(ifp, 38, SEEK_CUR); case 0xb4c2: \/\/ 46274 fseek(ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952) { height = 5412; width = 7216; left_margin = 7; filters = 0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek(ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek(ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width, height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } c = height * width \/ 1000000; if (c == 32) c--; sprintf(model, \"Ixpress %d-Mp\", c); load_raw = &LibRaw::imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &LibRaw::unpacked_load_raw; } maximum = 0xffff; break; case 0xc516: \/* 50454, Sinar tag *\/ case 0xc517: \/\/ 50455 if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len))) break; if (fread(cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; \/\/ cbuf to be free'ed in recycle cbuf[len - 1] = 0; for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\\n')) if (!strncmp(++cp, \"Neutral \", 8)) sscanf(cp + 8, \"%f %f %f\", cam_mul, cam_mul + 1, cam_mul + 2); free(cbuf); break; case 0xc51a: \/\/ 50458 if (!make[0]) strcpy(make, \"Hasselblad\"); break; case 0xc51b: \/* 50459, Hasselblad tag *\/ if (!libraw_internal_data.unpacker_data.hasselblad_parser_flag) { libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1; i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek(ifp, j + (get2(), get4()), SEEK_SET); parse_tiff_ifd(j); maximum = 0xffff; tiff_nifds = c; order = i; break; } case 0xc612: \/* 50706, DNGVersion *\/ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy(make, \"DNG\"); is_raw = 1; break; case 0xc614: \/* 50708, UniqueCameraModel *\/ stmread(imgdata.color.UniqueCameraModel, len, ifp); if (model[0]) break; strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } break; case 0xc616: \/* 50710, CFAPlaneColor *\/ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread(cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i = 16; i--;) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; tiff_ifd[ifd].t_filters = filters; break; case 0xc617: \/* 50711, CFALayout *\/ if (get2() == 2) tiff_ifd[ifd].t_fuji_width = fuji_width = 1; break; case 0x0123: \/\/ 291 case 0xc618: \/* 50712, LinearizationTable *\/ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE; tiff_ifd[ifd].lineartable_offset = ftell(ifp); tiff_ifd[ifd].lineartable_len = len; linear_table(len); break; case 0xc619: \/* 50713, BlackLevelRepeatDim *\/ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_fcblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[4] = cblack[4] = get2(); tiff_ifd[ifd].dng_levels.dng_fcblack[5] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = cblack[5] = get2(); if (cblack[4] * cblack[5] > (LIBRAW_CBLACK_SIZE - 7)) \/\/ Use last cblack item as DNG black level count tiff_ifd[ifd].dng_levels.dng_fcblack[4] = tiff_ifd[ifd].dng_levels.dng_fcblack[5] = tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = cblack[4] = cblack[5] = 1; break; case 0xf00c: if (!is_4K_RAFdata) { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) && (libraw_internal_data.unpacker_data.lenRAFData < 10240000)) { INT64 f_save = ftell(ifp); rafdata = (ushort *)malloc( sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData); fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); uchar *PrivateMknBuf = (uchar *)rafdata; int PrivateMknLength = libraw_internal_data.unpacker_data.lenRAFData << 1; for (int pos = 0; pos < PrivateMknLength - 16; pos++) { if (!memcmp(PrivateMknBuf + pos, \"TSNERDTS\", 8)) { imFuji.isTSNERDTS = 1; break; } } \/* 0xc000 tag version, second ushort; valid if the first ushort is 0 *\/ if (!rafdata[0]) imFuji.RAFDataVersion = rafdata[1]; int fj; for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++) { \/\/ find Tungsten WB if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2])) { if (rafdata[fi - 15] != fwb[0]) \/\/ 15 is offset of Tungsten WB from the first \/\/ preset, Fine Weather WB continue; for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3) { imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] = imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2]; } if (imFuji.RAFDataVersion == 0x260) { \/\/ X-Pro3 for (int iCCT = 0, ofst = fi+24; iCCT < 31; iCCT++, ofst += 3) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[ofst+1]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[ofst]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[ofst+2]; } free(rafdata); break; } fi += 96; for (fj = fi; fj < (fi + 15); fj += 3) { if (rafdata[fj] != rafdata[fi]) { for (int iCCT = 0, ofst = fj - 93; iCCT < 31; iCCT++, ofst += 3) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[ofst+1]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[ofst]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[ofst+2]; } break; } } free(rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; case 0xf00d: if (!is_4K_RAFdata) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1]; \/\/ free(rafdata); } break; case 0xc615: \/* 50709, LocalizedCameraModel *\/ stmread(imgdata.color.LocalizedCameraModel, len, ifp); break; case 0xf00a: \/\/ 61450 cblack[4] = cblack[5] = MIN(sqrt((double)len), 64); case 0xc61a: \/* 50714, BlackLevel *\/ if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) \/\/ LinearDNG, per-channel black { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; for (i = 0; i < 4 && i < len; i++) { tiff_ifd[ifd].dng_levels.dng_fcblack[i] = getreal(type); tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = tiff_ifd[ifd].dng_levels.dng_fcblack[i] + 0.5; } tiff_ifd[ifd].dng_levels.dng_fblack = tiff_ifd[ifd].dng_levels.dng_black = black = 0; } else if( tiff_ifd[ifd].samples > 1 \/\/ Linear DNG w repeat dim && (tiff_ifd[ifd].samples * cblack[4] * cblack[5] == len)) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_cblack[LIBRAW_CBLACK_SIZE-1] = cblack[LIBRAW_CBLACK_SIZE-1] = len; for (i = 0; i < len && i < LIBRAW_CBLACK_SIZE-7; i++) { tiff_ifd[ifd].dng_levels.dng_fcblack[i+6] = getreal(type); tiff_ifd[ifd].dng_levels.dng_cblack[i+6] = cblack[i+6] = tiff_ifd[ifd].dng_levels.dng_fcblack[i+6] + 0.5; } } else if ((cblack[4] * cblack[5] < 2) && len == 1) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_fblack = getreal(type); black = tiff_ifd[ifd].dng_levels.dng_black = tiff_ifd[ifd].dng_levels.dng_fblack; } else if (cblack[4] * cblack[5] <= len) { FORC(cblack[4] * cblack[5]) { tiff_ifd[ifd].dng_levels.dng_fcblack[6 + c] = getreal(type); cblack[6 + c] = tiff_ifd[ifd].dng_levels.dng_fcblack[6 + c]; } black = 0; FORC4 cblack[c] = 0; if (tag == 0xc61a) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; FORC(cblack[4] * cblack[5]) tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c]; tiff_ifd[ifd].dng_levels.dng_fblack = 0; tiff_ifd[ifd].dng_levels.dng_black = 0; FORC4 tiff_ifd[ifd].dng_levels.dng_fcblack[c] = tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0; } } break; case 0xc61b: \/* 50715, BlackLevelDeltaH *\/ case 0xc61c: \/* 50716, BlackLevelDeltaV *\/ for (num = i = 0; i < len && i < 65536; i++) num += getreal(type); if (len > 0) { black += num \/ len + 0.5; tiff_ifd[ifd].dng_levels.dng_fblack += num \/ float(len); tiff_ifd[ifd].dng_levels.dng_black += num \/ len + 0.5; tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; } break; case 0xc61d: \/* 50717, WhiteLevel *\/ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE; tiff_ifd[ifd].dng_levels.dng_whitelevel[0] = maximum = getint(type); if (tiff_ifd[ifd].samples > 1) \/\/ Linear DNG case for (i = 1; i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type); break; case 0xc61e: \/* DefaultScale *\/ { float q1 = getreal(type); float q2 = getreal(type); if (q1 > 0.00001f && q2 > 0.00001f) { pixel_aspect = q1 \/ q2; if (pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; } } break; case 0xc61f: \/* 50719, DefaultCropOrigin *\/ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN; tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type); if (!strncasecmp(make, \"SONY\", 4)) { imgdata.sizes.raw_inset_crop.cleft = tiff_ifd[ifd].dng_levels.default_crop[0]; imgdata.sizes.raw_inset_crop.ctop = tiff_ifd[ifd].dng_levels.default_crop[1]; } } break; case 0xc620: \/* 50720, DefaultCropSize *\/ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE; tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type); if (!strncasecmp(make, \"SONY\", 4)) { imgdata.sizes.raw_inset_crop.cwidth = tiff_ifd[ifd].dng_levels.default_crop[2]; imgdata.sizes.raw_inset_crop.cheight = tiff_ifd[ifd].dng_levels.default_crop[3]; } } break; case 0x74c7: if ((len == 2) && !strncasecmp(make, \"SONY\", 4)) { imgdata.sizes.raw_inset_crop.cleft = get4(); imgdata.sizes.raw_inset_crop.ctop = get4(); } break; case 0x74c8: if ((len == 2) && !strncasecmp(make, \"SONY\", 4)) { imgdata.sizes.raw_inset_crop.cwidth = get4(); imgdata.sizes.raw_inset_crop.cheight = get4(); } break; case 0xc65a: \/\/ 50778 tiff_ifd[ifd].dng_color[0].illuminant = get2(); tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 0xc65b: \/\/ 50779 tiff_ifd[ifd].dng_color[1].illuminant = get2(); tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 0xc621: \/* 50721, ColorMatrix1 *\/ case 0xc622: \/* 50722, ColorMatrix2 *\/ { int chan = (len == 9) ? 3 : (len == 12 ? 4 : 0); i = tag == 0xc621 ? 0 : 1; if (chan) { tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX; imHassy.nIFD_CM[i] = ifd; } FORC(chan) for (j = 0; j < 3; j++) { tiff_ifd[ifd].dng_color[i].colormatrix[c][j] = cm[c][j] = getreal(type); } use_cm = 1; } break; case 0xc714: \/* ForwardMatrix1 *\/ case 0xc715: \/* ForwardMatrix2 *\/ { int chan = (len == 9) ? 3 : (len == 12 ? 4 : 0); i = tag == 0xc714 ? 0 : 1; if (chan) tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; for (j = 0; j < 3; j++) FORC(chan) { tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] = fm[j][c] = getreal(type); } } break; case 0xc623: \/* 50723, CameraCalibration1 *\/ case 0xc624: \/* 50724, CameraCalibration2 *\/ { int chan = (len == 9) ? 3 : (len == 16 ? 4 : 0); j = tag == 0xc623 ? 0 : 1; if (chan) tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION; for (i = 0; i < chan; i++) FORC(chan) { tiff_ifd[ifd].dng_color[j].calibration[i][c] = cc[i][c] = getreal(type); } } break; case 0xc627: \/* 50727, AnalogBalance *\/ if (len >= 3) tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE; for (c = 0; c < len && c < 4; c++) { tiff_ifd[ifd].dng_levels.analogbalance[c] = ab[c] = getreal(type); } break; case 0xc628: \/* 50728, AsShotNeutral *\/ if (len >= 3) tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ASSHOTNEUTRAL; for (c = 0; c < len && c < 4; c++) tiff_ifd[ifd].dng_levels.asshotneutral[c] = asn[c] = getreal(type); break; case 0xc629: \/* 50729, AsShotWhiteXY *\/ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] \/= LibRaw_constants::d65_white[c]; break; case 0xc62a: \/* DNG: 50730 BaselineExposure *\/ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BASELINEEXPOSURE; tiff_ifd[ifd].dng_levels.baseline_exposure = getreal(type); break; case 0xc62e: \/* DNG: 50734 LinearResponseLimit *\/ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINEARRESPONSELIMIT; tiff_ifd[ifd].dng_levels.LinearResponseLimit = getreal(type); break; case 0xc634: \/* 50740 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private *\/ if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SKIP_MAKERNOTES)) { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, \"Adobe\")) { order = 0x4d4d; \/\/ Adobe header is always in \"MM\" \/ big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, \"Pano\", 4)) { \/\/ PanasonicRaw, yes, they use \"Pano\" as signature parseAdobePanoMakernote(); } if (!strncmp(mbuf, \"MakN\", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; INT64 save_pos = ifp->tell(); parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); curr_pos = save_pos + MakN_length - 6; fseek(ifp, curr_pos, SEEK_SET); fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, \"Pano \", 4)) { parseAdobePanoMakernote(); } if (!strncmp(mbuf, \"RAF \", 4)) { \/\/ Fujifilm Raw, AdobeRAF parseAdobeRAFMakernote(); } if (!strncmp(mbuf, \"SR2 \", 4)) { order = 0x4d4d; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; unsigned *buf_SR2; unsigned entries, tag, type, len, save; unsigned SR2SubIFDOffset = 0; unsigned SR2SubIFDLength = 0; unsigned SR2SubIFDKey = 0; int base = curr_pos + 6 - pos_in_original_raw; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 0x7200) { SR2SubIFDOffset = get4(); } else if (tag == 0x7201) { SR2SubIFDLength = get4(); } else if (tag == 0x7221) { SR2SubIFDKey = get4(); } fseek(ifp, save, SEEK_SET); } if (SR2SubIFDLength && (SR2SubIFDLength < 10240000) && (buf_SR2 = (unsigned *)malloc(SR2SubIFDLength + 1024))) { \/\/ 1024b for safety fseek(ifp, SR2SubIFDOffset + base, SEEK_SET); fread(buf_SR2, SR2SubIFDLength, 1, ifp); sony_decrypt(buf_SR2, SR2SubIFDLength \/ 4, 1, SR2SubIFDKey); parseSonySR2((uchar *)buf_SR2, SR2SubIFDOffset, SR2SubIFDLength, AdobeDNG); free(buf_SR2); } } \/* SR2 processed *\/ break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, \"RICOH\") && ((sget2((uchar *)mbuf + 6) == 0x4949) || (sget2((uchar *)mbuf + 6) == 0x4d4d))) { is_PentaxRicohMakernotes = 1; } if (!strcmp(mbuf, \"PENTAX \") || !strcmp(mbuf, \"SAMSUNG\") || is_PentaxRicohMakernotes) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } if (dng_version) { break; } parse_minolta(j = get4() + base); fseek(ifp, j, SEEK_SET); parse_tiff_ifd(base); break; case 0xc640: \/\/ 50752 read_shorts(cr2_slice, 3); break; case 0xc68b: \/* 50827, OriginalRawFileName *\/ stmread(imgdata.color.OriginalRawFileName, len, ifp); break; case 0xc68d: \/* 50829 ActiveArea *\/ tiff_ifd[ifd].t_tm=top_margin = getint(type); tiff_ifd[ifd].t_lm = left_margin = getint(type); tiff_ifd[ifd].t_vheight = height = getint(type) - top_margin; tiff_ifd[ifd].t_vwidth = width = getint(type) - left_margin; break; case 0xc68e: \/* 50830 MaskedAreas *\/ for (i = 0; i < len && i < 32; i++) ((int *)mask)[i] = getint(type); black = 0; break; case 0xc71a: \/* 50970, PreviewColorSpace *\/ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS; tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type); break; case 0xc741: \/* 51009, OpcodeList2 *\/ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2; tiff_ifd[ifd].opcode2_offset = meta_offset = ftell(ifp); break; case 0xfd04: \/* 64772, Kodak P-series *\/ if (len < 13) break; fseek(ifp, 16, SEEK_CUR); data_offset = get4(); fseek(ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &LibRaw::packed_load_raw; break; case 0xfe02: \/\/ 65026 if (type == 2) fgets(model2, 64, ifp); } fseek(ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length))) { fseek(ifp, sony_offset, SEEK_SET); fread(buf, sony_length, 1, ifp); sony_decrypt(buf, sony_length \/ 4, 1, sony_key); parseSonySR2((uchar *)buf, sony_offset, sony_length, nonDNG); free(buf); } for (i = 0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC if (fabs(asn[c]) > 0.0001) cam_mul[c] = 1 \/ asn[c]; } if (!use_cm) FORCC if (fabs(cc[c][c]) > 0.0001) pre_mul[c] \/= cc[c][c]; return 0; }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":459456,"input":"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 *\/ { \/* 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; 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_npar ; 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! *\/ (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...*\/ 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)(tail - RExC_emit_start), 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 EXACTFU | EXACTFU EXACTFU_SS | EXACTFU EXACTFA | EXACTFA EXACTL | EXACTL EXACTFLU8 | EXACTFLU8 *\/ #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \\ ? NOTHING \\ : ( EXACT == (X) ) \\ ? EXACT \\ : ( EXACTFU == (X) || EXACTFU_SS == (X) ) \\ ? EXACTFU \\ : ( EXACTFA == (X) ) \\ ? EXACTFA \\ : ( 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 = RExC_open_parens[paren]; end = 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) == 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) == 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: 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: *\/ 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 *\/ { \/* Fatal warnings may leak the regexp without this: *\/ SAVEFREESV(RExC_rx_sv); 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)); (void)ReREFCNT_inc(RExC_rx_sv); } 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) { RExC_open_parens[ARG(nxt1)]=oscan; \/*open->CURLYM*\/ RExC_close_parens[ARG(nxt1)]=nxt+2; \/*close->while*\/ } \/* 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) { RExC_open_parens[ARG(nxt1)]=oscan; \/*open->CURLYM*\/ RExC_close_parens[ARG(nxt1)]=nxt2+1; \/*close->NOTHING*\/ } 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: *\/ 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; if (UTF) old = utf8_hop((U8*)s, old) - (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; 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 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 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: if (FLAGS(scan) == _CC_ASCII) { my_invlist = invlist_clone(PL_XPosix_ptrs[_CC_ASCII]); } else { _invlist_intersection(PL_XPosix_ptrs[FLAGS(scan)], PL_XPosix_ptrs[_CC_ASCII], &my_invlist); } goto join_posix; case NPOSIXD: case NPOSIXU: invert = 1; \/* FALLTHROUGH *\/ case POSIXD: case POSIXU: my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)]); \/* 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: 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)); minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (scan->flags) { if (deltanext) { FAIL(\"Variable length lookbehind not implemented\"); } else if (minnext > (I32)U8_MAX) { FAIL2(\"Lookbehind longer than %\" UVuf \" not implemented\", (UV)U8_MAX); } scan->flags = (U8)minnext; } 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)); *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f,depth+1); if (scan->flags) { if (deltanext) { FAIL(\"Variable length lookbehind not implemented\"); } else if (*minnextp > (I32)U8_MAX) { FAIL2(\"Lookbehind longer than %\" UVuf \" not implemented\", (UV)U8_MAX); } scan->flags = (U8)*minnextp; } *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. *\/ 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) 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; } } 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 *\/ }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":332635,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if ((length > PNG_UINT_31_MAX) || (length > GetBlobSize(image)) || (count < 4)) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 9) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id >= MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS-1; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { \/* Read global PLTE. *\/ if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (((p-chunk) < (long) length) && *p) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; if (SetImageBackgroundColor(image,exception) == MagickFalse) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || (length % 2) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { if ((MagickSizeType) loop_iters > GetMagickResourceLimit(ListLengthResource)) loop_iters=GetMagickResourceLimit(ListLengthResource); if (loop_iters >= 2147483647L) loop_iters=2147483647L; mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] > 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { if (prev != (Quantum *) NULL) prev=(Quantum *) RelinquishMagickMemory(prev); if (next != (Quantum *) NULL) next=(Quantum *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (Quantum *) NULL) break; q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers && image->next) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); image=DestroyImageList(image); if (next_image == (Image *) NULL) { mng_info=MngInfoFreeStruct(mng_info); return((Image *) NULL); } image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":9422,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MaxTextExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False when converting or mogrifying *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; \/* Skip nominal layer count, frame count, and play time *\/ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\", \"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, \"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (*p && ((p-chunk) < (ssize_t) length)) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters \", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { \/* Interpolate *\/ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))\/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ else { \/* Interpolate *\/ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage();\"); return(image); }","output":{"is_vulnerable":"True","vulnerability_types":["Out-of-bounds Read"],"explanation":"In ImageMagick before 6.9.9-0 and 7.x before 7.0.6-1, the ReadOneMNGImage function in coders\/png.c has an out-of-bounds read with the MNG CLIP chunk.","severity_level":"NoInfo","cwe":"CWE-125","cve":"CVE-2017-13139"}} -{"idx":212954,"input":"int cli_scanpe(cli_ctx *ctx) { uint16_t e_magic; \/* DOS signature (\"MZ\") *\/ uint16_t nsections; uint32_t e_lfanew; \/* address of new exe header *\/ uint32_t ep, vep; \/* entry point (raw, virtual) *\/ uint8_t polipos = 0; time_t timestamp; struct pe_image_file_hdr file_hdr; union { struct pe_image_optional_hdr64 opt64; struct pe_image_optional_hdr32 opt32; } pe_opt; struct pe_image_section_hdr *section_hdr; char sname[9], epbuff[4096], *tempfile; uint32_t epsize; ssize_t bytes, at; unsigned int i, found, upx_success = 0, min = 0, max = 0, err, overlays = 0; unsigned int ssize = 0, dsize = 0, dll = 0, pe_plus = 0, corrupted_cur; int (*upxfn)(char *, uint32_t, char *, uint32_t *, uint32_t, uint32_t, uint32_t) = NULL; char *src = NULL, *dest = NULL; int ndesc, ret = CL_CLEAN, upack = 0, native=0; size_t fsize; uint32_t valign, falign, hdr_size, j; struct cli_exe_section *exe_sections; struct cli_matcher *md5_sect; char timestr[32]; struct pe_image_data_dir *dirs; struct cli_bc_ctx *bc_ctx; fmap_t *map; struct cli_pe_hook_data pedata; #ifdef HAVE__INTERNAL__SHA_COLLECT int sha_collect = ctx->sha_collect; #endif const char * virname = NULL; uint32_t viruses_found = 0; if(!ctx) { cli_errmsg(\"cli_scanpe: ctx == NULL\\n\"); return CL_ENULLARG; } map = *ctx->fmap; if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic)) { cli_dbgmsg(\"Can't read DOS signature\\n\"); return CL_CLEAN; } if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) { cli_dbgmsg(\"Invalid DOS signature\\n\"); return CL_CLEAN; } if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) { cli_dbgmsg(\"Can't read new header address\\n\"); \/* truncated header? *\/ if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } e_lfanew = EC32(e_lfanew); cli_dbgmsg(\"e_lfanew == %d\\n\", e_lfanew); if(!e_lfanew) { cli_dbgmsg(\"Not a PE file\\n\"); return CL_CLEAN; } if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) { \/* bad information in e_lfanew - probably not a PE file *\/ cli_dbgmsg(\"Can't read file header\\n\"); return CL_CLEAN; } if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) { cli_dbgmsg(\"Invalid PE signature (probably NE file)\\n\"); return CL_CLEAN; } if(EC16(file_hdr.Characteristics) & 0x2000) { cli_dbgmsg(\"File type: DLL\\n\"); dll = 1; } else if(EC16(file_hdr.Characteristics) & 0x01) { cli_dbgmsg(\"File type: Executable\\n\"); } switch(EC16(file_hdr.Machine)) { case 0x0: cli_dbgmsg(\"Machine type: Unknown\\n\"); break; case 0x14c: cli_dbgmsg(\"Machine type: 80386\\n\"); break; case 0x14d: cli_dbgmsg(\"Machine type: 80486\\n\"); break; case 0x14e: cli_dbgmsg(\"Machine type: 80586\\n\"); break; case 0x160: cli_dbgmsg(\"Machine type: R30000 (big-endian)\\n\"); break; case 0x162: cli_dbgmsg(\"Machine type: R3000\\n\"); break; case 0x166: cli_dbgmsg(\"Machine type: R4000\\n\"); break; case 0x168: cli_dbgmsg(\"Machine type: R10000\\n\"); break; case 0x184: cli_dbgmsg(\"Machine type: DEC Alpha AXP\\n\"); break; case 0x284: cli_dbgmsg(\"Machine type: DEC Alpha AXP 64bit\\n\"); break; case 0x1f0: cli_dbgmsg(\"Machine type: PowerPC\\n\"); break; case 0x200: cli_dbgmsg(\"Machine type: IA64\\n\"); break; case 0x268: cli_dbgmsg(\"Machine type: M68k\\n\"); break; case 0x266: cli_dbgmsg(\"Machine type: MIPS16\\n\"); break; case 0x366: cli_dbgmsg(\"Machine type: MIPS+FPU\\n\"); break; case 0x466: cli_dbgmsg(\"Machine type: MIPS16+FPU\\n\"); break; case 0x1a2: cli_dbgmsg(\"Machine type: Hitachi SH3\\n\"); break; case 0x1a3: cli_dbgmsg(\"Machine type: Hitachi SH3-DSP\\n\"); break; case 0x1a4: cli_dbgmsg(\"Machine type: Hitachi SH3-E\\n\"); break; case 0x1a6: cli_dbgmsg(\"Machine type: Hitachi SH4\\n\"); break; case 0x1a8: cli_dbgmsg(\"Machine type: Hitachi SH5\\n\"); break; case 0x1c0: cli_dbgmsg(\"Machine type: ARM\\n\"); break; case 0x1c2: cli_dbgmsg(\"Machine type: THUMB\\n\"); break; case 0x1d3: cli_dbgmsg(\"Machine type: AM33\\n\"); break; case 0x520: cli_dbgmsg(\"Machine type: Infineon TriCore\\n\"); break; case 0xcef: cli_dbgmsg(\"Machine type: CEF\\n\"); break; case 0xebc: cli_dbgmsg(\"Machine type: EFI Byte Code\\n\"); break; case 0x9041: cli_dbgmsg(\"Machine type: M32R\\n\"); break; case 0xc0ee: cli_dbgmsg(\"Machine type: CEE\\n\"); break; case 0x8664: cli_dbgmsg(\"Machine type: AMD64\\n\"); break; default: cli_dbgmsg(\"Machine type: ** UNKNOWN ** (0x%x)\\n\", EC16(file_hdr.Machine)); } nsections = EC16(file_hdr.NumberOfSections); if(nsections < 1 || nsections > 96) { if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } if(!ctx->corrupted_input) { if(nsections) cli_warnmsg(\"PE file contains %d sections\\n\", nsections); else cli_warnmsg(\"PE file contains no sections\\n\"); } return CL_CLEAN; } cli_dbgmsg(\"NumberOfSections: %d\\n\", nsections); timestamp = (time_t) EC32(file_hdr.TimeDateStamp); cli_dbgmsg(\"TimeDateStamp: %s\", cli_ctime(×tamp, timestr, sizeof(timestr))); cli_dbgmsg(\"SizeOfOptionalHeader: %x\\n\", EC16(file_hdr.SizeOfOptionalHeader)); if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg(\"SizeOfOptionalHeader too small\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at = e_lfanew + sizeof(struct pe_image_file_hdr); if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg(\"Can't read optional file header\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_optional_hdr32); \/* This will be a chicken and egg problem until we drop 9x *\/ if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) { if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) { \/* FIXME: need to play around a bit more with xp64 *\/ cli_dbgmsg(\"Incorrect SizeOfOptionalHeader for PE32+\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } pe_plus = 1; } if(!pe_plus) { \/* PE *\/ if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) { \/* Seek to the end of the long header *\/ at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32); } if(DCONF & PE_CONF_UPACK) upack = (EC16(file_hdr.SizeOfOptionalHeader)==0x148); vep = EC32(optional_hdr32.AddressOfEntryPoint); hdr_size = EC32(optional_hdr32.SizeOfHeaders); cli_dbgmsg(\"File format: PE\\n\"); cli_dbgmsg(\"MajorLinkerVersion: %d\\n\", optional_hdr32.MajorLinkerVersion); cli_dbgmsg(\"MinorLinkerVersion: %d\\n\", optional_hdr32.MinorLinkerVersion); cli_dbgmsg(\"SizeOfCode: 0x%x\\n\", EC32(optional_hdr32.SizeOfCode)); cli_dbgmsg(\"SizeOfInitializedData: 0x%x\\n\", EC32(optional_hdr32.SizeOfInitializedData)); cli_dbgmsg(\"SizeOfUninitializedData: 0x%x\\n\", EC32(optional_hdr32.SizeOfUninitializedData)); cli_dbgmsg(\"AddressOfEntryPoint: 0x%x\\n\", vep); cli_dbgmsg(\"BaseOfCode: 0x%x\\n\", EC32(optional_hdr32.BaseOfCode)); cli_dbgmsg(\"SectionAlignment: 0x%x\\n\", EC32(optional_hdr32.SectionAlignment)); cli_dbgmsg(\"FileAlignment: 0x%x\\n\", EC32(optional_hdr32.FileAlignment)); cli_dbgmsg(\"MajorSubsystemVersion: %d\\n\", EC16(optional_hdr32.MajorSubsystemVersion)); cli_dbgmsg(\"MinorSubsystemVersion: %d\\n\", EC16(optional_hdr32.MinorSubsystemVersion)); cli_dbgmsg(\"SizeOfImage: 0x%x\\n\", EC32(optional_hdr32.SizeOfImage)); cli_dbgmsg(\"SizeOfHeaders: 0x%x\\n\", hdr_size); cli_dbgmsg(\"NumberOfRvaAndSizes: %d\\n\", EC32(optional_hdr32.NumberOfRvaAndSizes)); dirs = optional_hdr32.DataDirectory; } else { \/* PE+ *\/ \/* read the remaining part of the header *\/ if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) { cli_dbgmsg(\"Can't read optional file header\\n\"); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32); vep = EC32(optional_hdr64.AddressOfEntryPoint); hdr_size = EC32(optional_hdr64.SizeOfHeaders); cli_dbgmsg(\"File format: PE32+\\n\"); cli_dbgmsg(\"MajorLinkerVersion: %d\\n\", optional_hdr64.MajorLinkerVersion); cli_dbgmsg(\"MinorLinkerVersion: %d\\n\", optional_hdr64.MinorLinkerVersion); cli_dbgmsg(\"SizeOfCode: 0x%x\\n\", EC32(optional_hdr64.SizeOfCode)); cli_dbgmsg(\"SizeOfInitializedData: 0x%x\\n\", EC32(optional_hdr64.SizeOfInitializedData)); cli_dbgmsg(\"SizeOfUninitializedData: 0x%x\\n\", EC32(optional_hdr64.SizeOfUninitializedData)); cli_dbgmsg(\"AddressOfEntryPoint: 0x%x\\n\", vep); cli_dbgmsg(\"BaseOfCode: 0x%x\\n\", EC32(optional_hdr64.BaseOfCode)); cli_dbgmsg(\"SectionAlignment: 0x%x\\n\", EC32(optional_hdr64.SectionAlignment)); cli_dbgmsg(\"FileAlignment: 0x%x\\n\", EC32(optional_hdr64.FileAlignment)); cli_dbgmsg(\"MajorSubsystemVersion: %d\\n\", EC16(optional_hdr64.MajorSubsystemVersion)); cli_dbgmsg(\"MinorSubsystemVersion: %d\\n\", EC16(optional_hdr64.MinorSubsystemVersion)); cli_dbgmsg(\"SizeOfImage: 0x%x\\n\", EC32(optional_hdr64.SizeOfImage)); cli_dbgmsg(\"SizeOfHeaders: 0x%x\\n\", hdr_size); cli_dbgmsg(\"NumberOfRvaAndSizes: %d\\n\", EC32(optional_hdr64.NumberOfRvaAndSizes)); dirs = optional_hdr64.DataDirectory; } switch(pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)) { case 0: cli_dbgmsg(\"Subsystem: Unknown\\n\"); break; case 1: cli_dbgmsg(\"Subsystem: Native (svc)\\n\"); native = 1; break; case 2: cli_dbgmsg(\"Subsystem: Win32 GUI\\n\"); break; case 3: cli_dbgmsg(\"Subsystem: Win32 console\\n\"); break; case 5: cli_dbgmsg(\"Subsystem: OS\/2 console\\n\"); break; case 7: cli_dbgmsg(\"Subsystem: POSIX console\\n\"); break; case 8: cli_dbgmsg(\"Subsystem: Native Win9x driver\\n\"); break; case 9: cli_dbgmsg(\"Subsystem: WinCE GUI\\n\"); break; case 10: cli_dbgmsg(\"Subsystem: EFI application\\n\"); break; case 11: cli_dbgmsg(\"Subsystem: EFI driver\\n\"); break; case 12: cli_dbgmsg(\"Subsystem: EFI runtime driver\\n\"); break; case 13: cli_dbgmsg(\"Subsystem: EFI ROM image\\n\"); break; case 14: cli_dbgmsg(\"Subsystem: Xbox\\n\"); break; case 16: cli_dbgmsg(\"Subsystem: Boot application\\n\"); break; default: cli_dbgmsg(\"Subsystem: ** UNKNOWN ** (0x%x)\\n\", pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)); } cli_dbgmsg(\"------------------------------------\\n\"); if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment)) || (pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment))%0x1000)) { cli_dbgmsg(\"Bad virtual alignment\\n\"); cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment)) || (pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment))%0x200)) { cli_dbgmsg(\"Bad file alignment\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); return CL_VIRUS; } fsize = map->len; section_hdr = (struct pe_image_section_hdr *) cli_calloc(nsections, sizeof(struct pe_image_section_hdr)); if(!section_hdr) { cli_dbgmsg(\"Can't allocate memory for section headers\\n\"); return CL_EMEM; } exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section)); if(!exe_sections) { cli_dbgmsg(\"Can't allocate memory for section headers\\n\"); free(section_hdr); return CL_EMEM; } valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment); falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment); if(fmap_readn(map, section_hdr, at, sizeof(struct pe_image_section_hdr)*nsections) != (int)(nsections*sizeof(struct pe_image_section_hdr))) { cli_dbgmsg(\"Can't read section header\\n\"); cli_dbgmsg(\"Possibly broken PE file\\n\"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } at += sizeof(struct pe_image_section_hdr)*nsections; for(i = 0; falign!=0x200 && iexe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz)) exe_sections[i].rsz = fsize - exe_sections[i].raw; cli_dbgmsg(\"Section %d\\n\", i); cli_dbgmsg(\"Section name: %s\\n\", sname); cli_dbgmsg(\"Section data (from headers - in memory)\\n\"); cli_dbgmsg(\"VirtualSize: 0x%x 0x%x\\n\", exe_sections[i].uvsz, exe_sections[i].vsz); cli_dbgmsg(\"VirtualAddress: 0x%x 0x%x\\n\", exe_sections[i].urva, exe_sections[i].rva); cli_dbgmsg(\"SizeOfRawData: 0x%x 0x%x\\n\", exe_sections[i].ursz, exe_sections[i].rsz); cli_dbgmsg(\"PointerToRawData: 0x%x 0x%x\\n\", exe_sections[i].uraw, exe_sections[i].raw); if(exe_sections[i].chr & 0x20) { cli_dbgmsg(\"Section contains executable code\\n\"); if(exe_sections[i].vsz < exe_sections[i].rsz) { cli_dbgmsg(\"Section contains free space\\n\"); \/* cli_dbgmsg(\"Dumping %d bytes\\n\", section_hdr.SizeOfRawData - section_hdr.VirtualSize); ddump(desc, section_hdr.PointerToRawData + section_hdr.VirtualSize, section_hdr.SizeOfRawData - section_hdr.VirtualSize, cli_gentemp(NULL)); *\/ } } if(exe_sections[i].chr & 0x20000000) cli_dbgmsg(\"Section's memory is executable\\n\"); if(exe_sections[i].chr & 0x80000000) cli_dbgmsg(\"Section's memory is writeable\\n\"); if (DETECT_BROKEN_PE && (!valign || (exe_sections[i].urva % valign))) { \/* Bad virtual alignment *\/ cli_dbgmsg(\"VirtualAddress is misaligned\\n\"); cli_dbgmsg(\"------------------------------------\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } if (exe_sections[i].rsz) { \/* Don't bother with virtual only sections *\/ if (exe_sections[i].raw >= fsize) { \/* really broken *\/ cli_dbgmsg(\"Broken PE file - Section %d starts beyond the end of file (Offset@ %lu, Total filesize %lu)\\n\", i, (unsigned long)exe_sections[i].raw, (unsigned long)fsize); cli_dbgmsg(\"------------------------------------\\n\"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; \/* no ninjas to see here! move along! *\/ } if(SCAN_ALGO && (DCONF & PE_CONF_POLIPOS) && !*sname && exe_sections[i].vsz > 40000 && exe_sections[i].vsz < 70000 && exe_sections[i].chr == 0xe0000060) polipos = i; \/* check MD5 section sigs *\/ md5_sect = ctx->engine->hm_mdb; if((DCONF & PE_CONF_MD5SECT) && md5_sect) { unsigned char md5_dig[16]; if(cli_hm_have_size(md5_sect, CLI_HASH_MD5, exe_sections[i].rsz) && cli_md5sect(map, &exe_sections[i], md5_dig) && cli_hm_scan(md5_dig, exe_sections[i].rsz, &virname, md5_sect, CLI_HASH_MD5) == CL_VIRUS) { cli_append_virus(ctx, virname); if(cli_hm_scan(md5_dig, fsize, NULL, ctx->engine->hm_fp, CLI_HASH_MD5) != CL_VIRUS) { if (!SCAN_ALL) { cli_dbgmsg(\"------------------------------------\\n\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } } viruses_found++; } } } cli_dbgmsg(\"------------------------------------\\n\"); if (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) { cli_dbgmsg(\"Found PE values with sign bit set\\n\"); free(section_hdr); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } if(!i) { if (DETECT_BROKEN_PE && exe_sections[i].urva!=hdr_size) { \/* Bad first section RVA *\/ cli_dbgmsg(\"First section is in the wrong place\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } min = exe_sections[i].rva; max = exe_sections[i].rva + exe_sections[i].rsz; } else { if (DETECT_BROKEN_PE && exe_sections[i].urva - exe_sections[i-1].urva != exe_sections[i-1].vsz) { \/* No holes, no overlapping, no virtual disorder *\/ cli_dbgmsg(\"Virtually misplaced section (wrong order, overlapping, non contiguous)\\n\"); cli_append_virus(ctx, \"Heuristics.Broken.Executable\"); free(section_hdr); free(exe_sections); return CL_VIRUS; } if(exe_sections[i].rva < min) min = exe_sections[i].rva; if(exe_sections[i].rva + exe_sections[i].rsz > max) { max = exe_sections[i].rva + exe_sections[i].rsz; overlays = exe_sections[i].raw + exe_sections[i].rsz; } } } free(section_hdr); if(!(ep = cli_rawaddr(vep, exe_sections, nsections, &err, fsize, hdr_size)) && err) { cli_dbgmsg(\"EntryPoint out of file\\n\"); free(exe_sections); if(DETECT_BROKEN_PE) { cli_append_virus(ctx,\"Heuristics.Broken.Executable\"); return CL_VIRUS; } return CL_CLEAN; } cli_dbgmsg(\"EntryPoint offset: 0x%x (%d)\\n\", ep, ep); if(pe_plus) { \/* Do not continue for PE32+ files *\/ free(exe_sections); return CL_CLEAN; } epsize = fmap_readn(map, epbuff, ep, 4096); \/* Disasm scan disabled since it's now handled by the bytecode *\/ \/* CLI_UNPTEMP(\"DISASM\",(exe_sections,0)); *\/ \/* if(disasmbuf((unsigned char*)epbuff, epsize, ndesc)) *\/ \/* ret = cli_scandesc(ndesc, ctx, CL_TYPE_PE_DISASM, 1, NULL, AC_SCAN_VIR); *\/ \/* close(ndesc); *\/ \/* CLI_TMPUNLK(); *\/ \/* free(tempfile); *\/ \/* if(ret == CL_VIRUS) { *\/ \/* free(exe_sections); *\/ \/* return ret; *\/ \/* } *\/ if(overlays) { int overlays_sz = fsize - overlays; if(overlays_sz > 0) { ret = cli_scanishield(ctx, overlays, overlays_sz); if(ret != CL_CLEAN) { free(exe_sections); return ret; } } } pedata.nsections = nsections; pedata.ep = ep; pedata.offset = 0; memcpy(&pedata.file_hdr, &file_hdr, sizeof(file_hdr)); memcpy(&pedata.opt32, &pe_opt.opt32, sizeof(pe_opt.opt32)); memcpy(&pedata.opt64, &pe_opt.opt64, sizeof(pe_opt.opt64)); memcpy(&pedata.dirs, dirs, sizeof(pedata.dirs)); pedata.e_lfanew = e_lfanew; pedata.overlays = overlays; pedata.overlays_sz = fsize - overlays; pedata.hdr_size = hdr_size; \/* Bytecode BC_PE_ALL hook *\/ bc_ctx = cli_bytecode_context_alloc(); if (!bc_ctx) { cli_errmsg(\"cli_scanpe: can't allocate memory for bc_ctx\\n\"); return CL_EMEM; } cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections); cli_bytecode_context_setctx(bc_ctx, ctx); ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_ALL, map); if (ret == CL_VIRUS || ret == CL_BREAK) { free(exe_sections); cli_bytecode_context_destroy(bc_ctx); return ret == CL_VIRUS ? CL_VIRUS : CL_CLEAN; } cli_bytecode_context_destroy(bc_ctx); \/* Attempt to detect some popular polymorphic viruses *\/ \/* W32.Parite.B *\/ if(SCAN_ALGO && (DCONF & PE_CONF_PARITE) && !dll && epsize == 4096 && ep == exe_sections[nsections - 1].raw) { const char *pt = cli_memstr(epbuff, 4040, \"\\x47\\x65\\x74\\x50\\x72\\x6f\\x63\\x41\\x64\\x64\\x72\\x65\\x73\\x73\\x00\", 15); if(pt) { pt += 15; if((((uint32_t)cli_readint32(pt) ^ (uint32_t)cli_readint32(pt + 4)) == 0x505a4f) && (((uint32_t)cli_readint32(pt + 8) ^ (uint32_t)cli_readint32(pt + 12)) == 0xffffb) && (((uint32_t)cli_readint32(pt + 16) ^ (uint32_t)cli_readint32(pt + 20)) == 0xb8)) { cli_append_virus(ctx,\"Heuristics.W32.Parite.B\"); if (!SCAN_ALL) { free(exe_sections); return CL_VIRUS; } viruses_found++; } } } \/* Kriz *\/ if(SCAN_ALGO && (DCONF & PE_CONF_KRIZ) && epsize >= 200 && CLI_ISCONTAINED(exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz, ep, 0x0fd2) && epbuff[1]=='\\x9c' && epbuff[2]=='\\x60') { enum {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSXORPRFX,KZSXOR,KZSDDELTA,KZSLOOP,KZSTOP}; uint8_t kzs[] = {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSTRASH,KZSXORPRFX,KZSXOR,KZSTRASH,KZSDDELTA,KZSTRASH,KZSLOOP,KZSTOP}; uint8_t *kzstate = kzs; uint8_t *kzcode = (uint8_t *)epbuff + 3; uint8_t kzdptr=0xff, kzdsize=0xff; int kzlen = 197, kzinitlen=0xffff, kzxorlen=-1; cli_dbgmsg(\"in kriz\\n\"); while(*kzstate!=KZSTOP) { uint8_t op; if(kzlen<=6) break; op = *kzcode++; kzlen--; switch (*kzstate) { case KZSTRASH: case KZSGETSIZE: { int opsz=0; switch(op) { case 0x81: kzcode+=5; kzlen-=5; break; case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbd: case 0xbe: case 0xbf: if(*kzstate==KZSGETSIZE && cli_readint32(kzcode)==0x0fd2) { kzinitlen = kzlen-5; kzdsize=op-0xb8; kzstate++; op=4; \/* fake the register to avoid breaking out *\/ cli_dbgmsg(\"kriz: using #%d as size counter\\n\", kzdsize); } opsz=4; case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4d: case 0x4e: case 0x4f: op&=7; if(op!=kzdptr && op!=kzdsize) { kzcode+=opsz; kzlen-=opsz; break; } default: kzcode--; kzlen++; kzstate++; } break; } case KZSCDELTA: if(op==0xe8 && (uint32_t)cli_readint32(kzcode) < 0xff) { kzlen-=*kzcode+4; kzcode+=*kzcode+4; kzstate++; } else *kzstate=KZSTOP; break; case KZSPDELTA: if((op&0xf8)==0x58 && (kzdptr=op-0x58)!=4) { kzstate++; cli_dbgmsg(\"kriz: using #%d as pointer\\n\", kzdptr); } else *kzstate=KZSTOP; break; case KZSXORPRFX: kzstate++; if(op==0x3e) break; case KZSXOR: if (op==0x80 && *kzcode==kzdptr+0xb0) { kzxorlen=kzlen; kzcode+=+6; kzlen-=+6; kzstate++; } else *kzstate=KZSTOP; break; case KZSDDELTA: if (op==kzdptr+0x48) kzstate++; else *kzstate=KZSTOP; break; case KZSLOOP: if (op==kzdsize+0x48 && *kzcode==0x75 && kzlen-(int8_t)kzcode[1]-3<=kzinitlen && kzlen-(int8_t)kzcode[1]>=kzxorlen) { cli_append_virus(ctx,\"Heuristics.W32.Kriz\"); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } cli_dbgmsg(\"kriz: loop out of bounds, corrupted sample?\\n\"); kzstate++; } } } \/* W32.Magistr.A\/B *\/ if(SCAN_ALGO && (DCONF & PE_CONF_MAGISTR) && !dll && (nsections>1) && (exe_sections[nsections - 1].chr & 0x80000000)) { uint32_t rsize, vsize, dam = 0; vsize = exe_sections[nsections - 1].uvsz; rsize = exe_sections[nsections - 1].rsz; if(rsize < exe_sections[nsections - 1].ursz) { rsize = exe_sections[nsections - 1].ursz; dam = 1; } if(vsize >= 0x612c && rsize >= 0x612c && ((vsize & 0xff) == 0xec)) { int bw = rsize < 0x7000 ? rsize : 0x7000; char *tbuff; if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) { if(cli_memstr(tbuff, 4091, \"\\xe8\\x2c\\x61\\x00\\x00\", 5)) { cli_append_virus(ctx, dam ? \"Heuristics.W32.Magistr.A.dam\" : \"Heuristics.W32.Magistr.A\"); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } } } else if(rsize >= 0x7000 && vsize >= 0x7000 && ((vsize & 0xff) == 0xed)) { int bw = rsize < 0x8000 ? rsize : 0x8000; char *tbuff; if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) { if(cli_memstr(tbuff, 4091, \"\\xe8\\x04\\x72\\x00\\x00\", 5)) { cli_append_virus(ctx,dam ? \"Heuristics.W32.Magistr.B.dam\" : \"Heuristics.W32.Magistr.B\"); free(exe_sections); if (!SCAN_ALL) return CL_VIRUS; viruses_found++; } } } } \/* W32.Polipos.A *\/ while(polipos && !dll && nsections > 2 && nsections < 13 && e_lfanew <= 0x800 && (EC16(optional_hdr32.Subsystem) == 2 || EC16(optional_hdr32.Subsystem) == 3) && EC16(file_hdr.Machine) == 0x14c && optional_hdr32.SizeOfStackReserve >= 0x80000) { uint32_t jump, jold, *jumps = NULL; uint8_t *code; unsigned int xsjs = 0; if(exe_sections[0].rsz > CLI_MAX_ALLOCATION) break; if(!exe_sections[0].rsz) break; if(!(code=fmap_need_off_once(map, exe_sections[0].raw, exe_sections[0].rsz))) break; for(i=0; i 1) continue; jump = cli_rawaddr(exe_sections[0].rva+i+5+cli_readint32(&code[i+1]), exe_sections, nsections, &err, fsize, hdr_size); if(err || !CLI_ISCONTAINED(exe_sections[polipos].raw, exe_sections[polipos].rsz, jump, 9)) continue; if(xsjs % 128 == 0) { if(xsjs == 1280) break; if(!(jumps=(uint32_t *)cli_realloc2(jumps, (xsjs+128)*sizeof(uint32_t)))) { free(exe_sections); return CL_EMEM; } } j=0; for(; j 1 && fsize > 64*1024 && fsize < 4*1024*1024) { if(dirs[2].Size) { struct swizz_stats *stats = cli_calloc(1, sizeof(*stats)); unsigned int m = 1000; ret = CL_CLEAN; if (!stats) ret = CL_EMEM; else { cli_parseres_special(EC32(dirs[2].VirtualAddress), EC32(dirs[2].VirtualAddress), map, exe_sections, nsections, fsize, hdr_size, 0, 0, &m, stats); if ((ret = cli_detect_swizz(stats)) == CL_VIRUS) { cli_append_virus(ctx,\"Heuristics.Trojan.Swizzor.Gen\"); } free(stats); } if (ret != CL_CLEAN) { if (!(ret == CL_VIRUS && SCAN_ALL)) { free(exe_sections); return ret; } viruses_found++; } } } \/* !!!!!!!!!!!!!! PACKERS START HERE !!!!!!!!!!!!!! *\/ corrupted_cur = ctx->corrupted_input; ctx->corrupted_input = 2; \/* caller will reset on return *\/ \/* UPX, FSG, MEW support *\/ \/* try to find the first section with physical size == 0 *\/ found = 0; if(DCONF & (PE_CONF_UPX | PE_CONF_FSG | PE_CONF_MEW)) { for(i = 0; i < (unsigned int) nsections - 1; i++) { if(!exe_sections[i].rsz && exe_sections[i].vsz && exe_sections[i + 1].rsz && exe_sections[i + 1].vsz) { found = 1; cli_dbgmsg(\"UPX\/FSG\/MEW: empty section found - assuming compression\\n\"); break; } } } \/* MEW support *\/ if (found && (DCONF & PE_CONF_MEW) && epsize>=16 && epbuff[0]=='\\xe9') { uint32_t fileoffset; char *tbuff; fileoffset = (vep + cli_readint32(epbuff + 1) + 5); while (fileoffset == 0x154 || fileoffset == 0x158) { uint32_t offdiff, uselzma; cli_dbgmsg (\"MEW: found MEW characteristics %08X + %08X + 5 = %08X\\n\", cli_readint32(epbuff + 1), vep, cli_readint32(epbuff + 1) + vep + 5); if(!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0))) break; if (fileoffset == 0x154) cli_dbgmsg(\"MEW: Win9x compatibility was set!\\n\"); else cli_dbgmsg(\"MEW: Win9x compatibility was NOT set!\\n\"); if((offdiff = cli_readint32(tbuff+1) - EC32(optional_hdr32.ImageBase)) <= exe_sections[i + 1].rva || offdiff >= exe_sections[i + 1].rva + exe_sections[i + 1].raw - 4) { cli_dbgmsg(\"MEW: ESI is not in proper section\\n\"); break; } offdiff -= exe_sections[i + 1].rva; if(!exe_sections[i + 1].rsz) { cli_dbgmsg(\"MEW: mew section is empty\\n\"); break; } ssize = exe_sections[i + 1].vsz; dsize = exe_sections[i].vsz; cli_dbgmsg(\"MEW: ssize %08x dsize %08x offdiff: %08x\\n\", ssize, dsize, offdiff); CLI_UNPSIZELIMITS(\"MEW\", MAX(ssize, dsize)); CLI_UNPSIZELIMITS(\"MEW\", MAX(ssize + dsize, exe_sections[i + 1].rsz)); if (exe_sections[i + 1].rsz < offdiff + 12 || exe_sections[i + 1].rsz > ssize) { cli_dbgmsg(\"MEW: Size mismatch: %08x\\n\", exe_sections[i + 1].rsz); break; } \/* allocate needed buffer *\/ if (!(src = cli_calloc (ssize + dsize, sizeof(char)))) { free(exe_sections); return CL_EMEM; } if((bytes = fmap_readn(map, src + dsize, exe_sections[i + 1].raw, exe_sections[i + 1].rsz)) != exe_sections[i + 1].rsz) { cli_dbgmsg(\"MEW: Can't read %d bytes [read: %lu]\\n\", exe_sections[i + 1].rsz, (unsigned long)bytes); free(exe_sections); free(src); return CL_EREAD; } cli_dbgmsg(\"MEW: %u (%08x) bytes read\\n\", (unsigned int)bytes, (unsigned int)bytes); \/* count offset to lzma proc, if lzma used, 0xe8 -> call *\/ if (tbuff[0x7b] == '\\xe8') { if (!CLI_ISCONTAINED(exe_sections[1].rva, exe_sections[1].vsz, cli_readint32(tbuff + 0x7c) + fileoffset + 0x80, 4)) { cli_dbgmsg(\"MEW: lzma proc out of bounds!\\n\"); free(src); break; \/* to next unpacker in chain *\/ } uselzma = cli_readint32(tbuff + 0x7c) - (exe_sections[0].rva - fileoffset - 0x80); } else { uselzma = 0; } CLI_UNPTEMP(\"MEW\",(src,exe_sections,0)); CLI_UNPRESULTS(\"MEW\",(unmew11(src, offdiff, ssize, dsize, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, uselzma, ndesc)),1,(src,0)); break; } } if(epsize<168) { free(exe_sections); return CL_CLEAN; } if (found || upack) { \/* Check EP for UPX vs. FSG vs. Upack *\/ \/* Upack 0.39 produces 2 types of executables * 3 sections: | 2 sections (one empty, I don't chech found if !upack, since it's in OR above): * mov esi, value | pusha * lodsd | call $+0x9 * push eax | * * Upack 1.1\/1.2 Beta produces [based on 2 samples (sUx) provided by aCaB]: * 2 sections * mov esi, value * loads * mov edi, eax * * Upack unknown [sample 0297729] * 3 sections * mov esi, value * push [esi] * jmp * *\/ \/* upack 0.39-3s + sample 0151477*\/ while(((upack && nsections == 3) && \/* 3 sections *\/ (( epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && \/* mov esi *\/ epbuff[5] == '\\xad' && epbuff[6] == '\\x50' \/* lodsd; push eax *\/ ) || \/* based on 0297729 sample from aCaB *\/ (epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && \/* mov esi *\/ epbuff[5] == '\\xff' && epbuff[6] == '\\x36' \/* push [esi] *\/ ) )) || ((!upack && nsections == 2) && \/* 2 sections *\/ (( \/* upack 0.39-2s *\/ epbuff[0] == '\\x60' && epbuff[1] == '\\xe8' && cli_readint32(epbuff+2) == 0x9 \/* pusha; call+9 *\/ ) || ( \/* upack 1.1\/1.2, based on 2 samples *\/ epbuff[0] == '\\xbe' && cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase) < min && \/* mov esi *\/ cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > 0 && epbuff[5] == '\\xad' && epbuff[6] == '\\x8b' && epbuff[7] == '\\xf8' \/* loads; mov edi, eax *\/ ) )) ) { uint32_t vma, off; int a,b,c; cli_dbgmsg(\"Upack characteristics found.\\n\"); a = exe_sections[0].vsz; b = exe_sections[1].vsz; if (upack) { cli_dbgmsg(\"Upack: var set\\n\"); c = exe_sections[2].vsz; ssize = exe_sections[0].ursz + exe_sections[0].uraw; off = exe_sections[0].rva; vma = EC32(optional_hdr32.ImageBase) + exe_sections[0].rva; } else { cli_dbgmsg(\"Upack: var NOT set\\n\"); c = exe_sections[1].rva; ssize = exe_sections[1].uraw; off = 0; vma = exe_sections[1].rva - exe_sections[1].uraw; } dsize = a+b+c; CLI_UNPSIZELIMITS(\"Upack\", MAX(MAX(dsize, ssize), exe_sections[1].ursz)); if (!CLI_ISCONTAINED(0, dsize, exe_sections[1].rva - off, exe_sections[1].ursz) || (upack && !CLI_ISCONTAINED(0, dsize, exe_sections[2].rva - exe_sections[0].rva, ssize)) || ssize > dsize) { cli_dbgmsg(\"Upack: probably malformed pe-header, skipping to next unpacker\\n\"); break; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); return CL_EMEM; } if(fmap_readn(map, dest, 0, ssize) != ssize) { cli_dbgmsg(\"Upack: Can't read raw data of section 0\\n\"); free(dest); break; } if(upack) memmove(dest + exe_sections[2].rva - exe_sections[0].rva, dest, ssize); if(fmap_readn(map, dest + exe_sections[1].rva - off, exe_sections[1].uraw, exe_sections[1].ursz) != exe_sections[1].ursz) { cli_dbgmsg(\"Upack: Can't read raw data of section 1\\n\"); free(dest); break; } CLI_UNPTEMP(\"Upack\",(dest,exe_sections,0)); CLI_UNPRESULTS(\"Upack\",(unupack(upack, dest, dsize, epbuff, vma, ep, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, ndesc)),1,(dest,0)); break; } } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\x87' && epbuff[1] == '\\x25') { \/* FSG v2.0 support - thanks to aCaB ! *\/ uint32_t newesi, newedi, newebx, newedx; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; CLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } newedx = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase); if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) { cli_dbgmsg(\"FSG: xchg out of bounds (%x), giving up\\n\", newedx); break; } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"Can't read raw data of section %d\\n\", i + 1); free(exe_sections); return CL_ESEEK; } dest = src + newedx - exe_sections[i + 1].rva; if(newedx < exe_sections[i + 1].rva || !CLI_ISCONTAINED(src, ssize, dest, 4)) { cli_dbgmsg(\"FSG: New ESP out of bounds\\n\"); break; } newedx = cli_readint32(dest) - EC32(optional_hdr32.ImageBase); if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) { cli_dbgmsg(\"FSG: New ESP (%x) is wrong\\n\", newedx); break; } dest = src + newedx - exe_sections[i + 1].rva; if(!CLI_ISCONTAINED(src, ssize, dest, 32)) { cli_dbgmsg(\"FSG: New stack out of bounds\\n\"); break; } newedi = cli_readint32(dest) - EC32(optional_hdr32.ImageBase); newesi = cli_readint32(dest + 4) - EC32(optional_hdr32.ImageBase); newebx = cli_readint32(dest + 16) - EC32(optional_hdr32.ImageBase); newedx = cli_readint32(dest + 20); if(newedi != exe_sections[i].rva) { cli_dbgmsg(\"FSG: Bad destination buffer (edi is %x should be %x)\\n\", newedi, exe_sections[i].rva); break; } if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) { cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\"); break; } if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newebx, 16)) { cli_dbgmsg(\"FSG: Array of functions out of bounds\\n\"); break; } newedx=cli_readint32(newebx + 12 - exe_sections[i + 1].rva + src) - EC32(optional_hdr32.ImageBase); cli_dbgmsg(\"FSG: found old EP @%x\\n\",newedx); if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(src); return CL_EMEM; } CLI_UNPTEMP(\"FSG\",(dest,exe_sections,0)); CLI_UNPRESULTSFSG2(\"FSG\",(unfsg_200(newesi - exe_sections[i + 1].rva + src, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, newedi, EC32(optional_hdr32.ImageBase), newedx, ndesc)),1,(dest,0)); break; } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min) { \/* FSG support - v. 1.33 (thx trog for the many samples) *\/ int sectcnt = 0; char *support; uint32_t newesi, newedi, oldep, gp, t; struct cli_exe_section *sections; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; CLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } if(!(t = cli_rawaddr(cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size)) && err ) { cli_dbgmsg(\"FSG: Support data out of padding area\\n\"); break; } gp = exe_sections[i + 1].raw - t; CLI_UNPSIZELIMITS(\"FSG\", gp); if(!(support = fmap_need_off_once(map, t, gp))) { cli_dbgmsg(\"Can't read %d bytes from padding area\\n\", gp); free(exe_sections); return CL_EREAD; } \/* newebx = cli_readint32(support) - EC32(optional_hdr32.ImageBase); Unused *\/ newedi = cli_readint32(support + 4) - EC32(optional_hdr32.ImageBase); \/* 1st dest *\/ newesi = cli_readint32(support + 8) - EC32(optional_hdr32.ImageBase); \/* Source *\/ if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) { cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\"); break; } if(newedi != exe_sections[i].rva) { cli_dbgmsg(\"FSG: Bad destination (is %x should be %x)\\n\", newedi, exe_sections[i].rva); break; } \/* Counting original sections *\/ for(t = 12; t < gp - 4; t += 4) { uint32_t rva = cli_readint32(support+t); if(!rva) break; rva -= EC32(optional_hdr32.ImageBase)+1; sectcnt++; if(rva % 0x1000) cli_dbgmsg(\"FSG: Original section %d is misaligned\\n\", sectcnt); if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) { cli_dbgmsg(\"FSG: Original section %d is out of bounds\\n\", sectcnt); break; } } if(t >= gp - 4 || cli_readint32(support + t)) { break; } if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { free(exe_sections); return CL_EMEM; } sections[0].rva = newedi; for(t = 1; t <= (uint32_t)sectcnt; t++) sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(optional_hdr32.ImageBase); if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"Can't read raw data of section %d\\n\", i); free(exe_sections); free(sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(sections); return CL_EMEM; } oldep = vep + 161 + 6 + cli_readint32(epbuff+163); cli_dbgmsg(\"FSG: found old EP @%x\\n\", oldep); CLI_UNPTEMP(\"FSG\",(dest,sections,exe_sections,0)); CLI_UNPRESULTSFSG1(\"FSG\",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0)); break; \/* were done with 1.33 *\/ } while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\\xbb' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min && epbuff[5] == '\\xbf' && epbuff[10] == '\\xbe' && vep >= exe_sections[i + 1].rva && vep - exe_sections[i + 1].rva > exe_sections[i + 1].rva - 0xe0 ) { \/* FSG support - v. 1.31 *\/ int sectcnt = 0; uint32_t gp, t = cli_rawaddr(cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size); char *support; uint32_t newesi = cli_readint32(epbuff+11) - EC32(optional_hdr32.ImageBase); uint32_t newedi = cli_readint32(epbuff+6) - EC32(optional_hdr32.ImageBase); uint32_t oldep = vep - exe_sections[i + 1].rva; struct cli_exe_section *sections; ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz; if(err) { cli_dbgmsg(\"FSG: Support data out of padding area\\n\"); break; } if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].raw) { cli_dbgmsg(\"FSG: Source buffer out of section bounds\\n\"); break; } if(newedi != exe_sections[i].rva) { cli_dbgmsg(\"FSG: Bad destination (is %x should be %x)\\n\", newedi, exe_sections[i].rva); break; } CLI_UNPSIZELIMITS(\"FSG\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize) { cli_dbgmsg(\"FSG: Size mismatch (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } gp = exe_sections[i + 1].raw - t; CLI_UNPSIZELIMITS(\"FSG\", gp) if(!(support = fmap_need_off_once(map, t, gp))) { cli_dbgmsg(\"Can't read %d bytes from padding area\\n\", gp); free(exe_sections); return CL_EREAD; } \/* Counting original sections *\/ for(t = 0; t < gp - 2; t += 2) { uint32_t rva = support[t]|(support[t+1]<<8); if (rva == 2 || rva == 1) break; rva = ((rva-2)<<12) - EC32(optional_hdr32.ImageBase); sectcnt++; if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) { cli_dbgmsg(\"FSG: Original section %d is out of bounds\\n\", sectcnt); break; } } if(t >= gp-10 || cli_readint32(support + t + 6) != 2) { break; } if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { free(exe_sections); return CL_EMEM; } sections[0].rva = newedi; for(t = 0; t <= (uint32_t)sectcnt - 1; t++) { sections[t+1].rva = (((support[t*2]|(support[t*2+1]<<8))-2)<<12)-EC32(optional_hdr32.ImageBase); } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"FSG: Can't read raw data of section %d\\n\", i); free(exe_sections); free(sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { free(exe_sections); free(sections); return CL_EMEM; } gp = 0xda + 6*(epbuff[16]=='\\xe8'); oldep = vep + gp + 6 + cli_readint32(src+gp+2+oldep); cli_dbgmsg(\"FSG: found old EP @%x\\n\", oldep); CLI_UNPTEMP(\"FSG\",(dest,sections,exe_sections,0)); CLI_UNPRESULTSFSG1(\"FSG\",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0)); break; \/* were done with 1.31 *\/ } if(found && (DCONF & PE_CONF_UPX)) { \/* UPX support *\/ \/* we assume (i + 1) is UPX1 *\/ ssize = exe_sections[i + 1].rsz; dsize = exe_sections[i].vsz + exe_sections[i + 1].vsz; CLI_UNPSIZELIMITS(\"UPX\", MAX(dsize, ssize)); if(ssize <= 0x19 || dsize <= ssize || dsize > CLI_MAX_ALLOCATION ) { cli_dbgmsg(\"UPX: Size mismatch or dsize too big (ssize: %d, dsize: %d)\\n\", ssize, dsize); free(exe_sections); return CL_CLEAN; } if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) { cli_dbgmsg(\"UPX: Can't read raw data of section %d\\n\", i+1); free(exe_sections); return CL_EREAD; } if((dest = (char *) cli_calloc(dsize + 8192, sizeof(char))) == NULL) { free(exe_sections); return CL_EMEM; } \/* try to detect UPX code *\/ if(cli_memstr(UPX_NRV2B, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2B, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg(\"UPX: Looks like a NRV2B decompression routine\\n\"); upxfn = upx_inflate2b; } else if(cli_memstr(UPX_NRV2D, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2D, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg(\"UPX: Looks like a NRV2D decompression routine\\n\"); upxfn = upx_inflate2d; } else if(cli_memstr(UPX_NRV2E, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2E, 24, epbuff + 0x69 + 8, 13)) { cli_dbgmsg(\"UPX: Looks like a NRV2E decompression routine\\n\"); upxfn = upx_inflate2e; } if(upxfn) { int skew = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase) - exe_sections[i + 1].rva; if(epbuff[1] != '\\xbe' || skew <= 0 || skew > 0xfff) { \/* FIXME: legit skews?? *\/ skew = 0; if(upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0) upx_success = 1; } else { cli_dbgmsg(\"UPX: UPX1 seems skewed by %d bytes\\n\", skew); if(upxfn(src + skew, ssize - skew, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep-skew) >= 0 || upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0) upx_success = 1; } if(upx_success) cli_dbgmsg(\"UPX: Successfully decompressed\\n\"); else cli_dbgmsg(\"UPX: Preferred decompressor failed\\n\"); } if(!upx_success && upxfn != upx_inflate2b) { if(upx_inflate2b(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2b(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg(\"UPX: NRV2B decompressor failed\\n\"); } else { upx_success = 1; cli_dbgmsg(\"UPX: Successfully decompressed with NRV2B\\n\"); } } if(!upx_success && upxfn != upx_inflate2d) { if(upx_inflate2d(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2d(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg(\"UPX: NRV2D decompressor failed\\n\"); } else { upx_success = 1; cli_dbgmsg(\"UPX: Successfully decompressed with NRV2D\\n\"); } } if(!upx_success && upxfn != upx_inflate2e) { if(upx_inflate2e(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2e(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) { cli_dbgmsg(\"UPX: NRV2E decompressor failed\\n\"); } else { upx_success = 1; cli_dbgmsg(\"UPX: Successfully decompressed with NRV2E\\n\"); } } if(cli_memstr(UPX_LZMA2, 20, epbuff + 0x2f, 20)) { uint32_t strictdsize=cli_readint32(epbuff+0x21), skew = 0; if(ssize > 0x15 && epbuff[0] == '\\x60' && epbuff[1] == '\\xbe') { skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase; if(skew!=0x15) skew = 0; } if(strictdsize<=dsize) upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0; } else if (cli_memstr(UPX_LZMA1, 20, epbuff + 0x39, 20)) { uint32_t strictdsize=cli_readint32(epbuff+0x2b), skew = 0; if(ssize > 0x15 && epbuff[0] == '\\x60' && epbuff[1] == '\\xbe') { skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase; if(skew!=0x15) skew = 0; } if(strictdsize<=dsize) upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0; } if(!upx_success) { cli_dbgmsg(\"UPX: All decompressors failed\\n\"); free(dest); } } if(upx_success) { free(exe_sections); CLI_UNPTEMP(\"UPX\/FSG\",(dest,0)); if((unsigned int) write(ndesc, dest, dsize) != dsize) { cli_dbgmsg(\"UPX\/FSG: Can't write %d bytes\\n\", dsize); free(tempfile); free(dest); close(ndesc); return CL_EWRITE; } free(dest); lseek(ndesc, 0, SEEK_SET); if(ctx->engine->keeptmp) cli_dbgmsg(\"UPX\/FSG: Decompressed data saved in %s\\n\", tempfile); cli_dbgmsg(\"***** Scanning decompressed file *****\\n\"); SHA_OFF; if((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS) { close(ndesc); CLI_TMPUNLK(); free(tempfile); SHA_RESET; return CL_VIRUS; } SHA_RESET; close(ndesc); CLI_TMPUNLK(); free(tempfile); return ret; } \/* Petite *\/ if(epsize<200) { free(exe_sections); return CL_CLEAN; } found = 2; if(epbuff[0] != '\\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 1].rva + EC32(optional_hdr32.ImageBase)) { if(nsections < 2 || epbuff[0] != '\\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 2].rva + EC32(optional_hdr32.ImageBase)) found = 0; else found = 1; } if(found && (DCONF & PE_CONF_PETITE)) { cli_dbgmsg(\"Petite: v2.%d compression detected\\n\", found); if(cli_readint32(epbuff + 0x80) == 0x163c988d) { cli_dbgmsg(\"Petite: level zero compression is not supported yet\\n\"); } else { dsize = max - min; CLI_UNPSIZELIMITS(\"Petite\", dsize); if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) { cli_dbgmsg(\"Petite: Can't allocate %d bytes\\n\", dsize); free(exe_sections); return CL_EMEM; } for(i = 0 ; i < nsections; i++) { if(exe_sections[i].raw) { if(!exe_sections[i].rsz || fmap_readn(map, dest + exe_sections[i].rva - min, exe_sections[i].raw, exe_sections[i].ursz) != exe_sections[i].ursz) { free(exe_sections); free(dest); return CL_CLEAN; } } } CLI_UNPTEMP(\"Petite\",(dest,exe_sections,0)); CLI_UNPRESULTS(\"Petite\",(petite_inflate2x_1to9(dest, min, max - min, exe_sections, nsections - (found == 1 ? 1 : 0), EC32(optional_hdr32.ImageBase),vep, ndesc, found, EC32(optional_hdr32.DataDirectory[2].VirtualAddress),EC32(optional_hdr32.DataDirectory[2].Size))),0,(dest,0)); } } \/* PESpin 1.1 *\/ if((DCONF & PE_CONF_PESPIN) && nsections > 1 && vep >= exe_sections[nsections - 1].rva && vep < exe_sections[nsections - 1].rva + exe_sections[nsections - 1].rsz - 0x3217 - 4 && memcmp(epbuff+4, \"\\xe8\\x00\\x00\\x00\\x00\\x8b\\x1c\\x24\\x83\\xc3\", 10) == 0) { char *spinned; CLI_UNPSIZELIMITS(\"PEspin\", fsize); if((spinned = (char *) cli_malloc(fsize)) == NULL) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) { cli_dbgmsg(\"PESpin: Can't read %lu bytes\\n\", (unsigned long)fsize); free(spinned); free(exe_sections); return CL_EREAD; } CLI_UNPTEMP(\"PESpin\",(spinned,exe_sections,0)); CLI_UNPRESULTS_(\"PEspin\",SPINCASE(),(unspin(spinned, fsize, exe_sections, nsections - 1, vep, ndesc, ctx)),0,(spinned,0)); } \/* yC 1.3 & variants *\/ if((DCONF & PE_CONF_YC) && nsections > 1 && (EC32(optional_hdr32.AddressOfEntryPoint) == exe_sections[nsections - 1].rva + 0x60)) { uint32_t ecx = 0; int16_t offset; \/* yC 1.3 *\/ if (!memcmp(epbuff, \"\\x55\\x8B\\xEC\\x53\\x56\\x57\\x60\\xE8\\x00\\x00\\x00\\x00\\x5D\\x81\\xED\", 15) && !memcmp(epbuff+0x26, \"\\x8D\\x3A\\x8B\\xF7\\x33\\xC0\\xEB\\x04\\x90\\xEB\\x01\\xC2\\xAC\", 13) && ((uint8_t)epbuff[0x13] == 0xB9) && ((uint16_t)(cli_readint16(epbuff+0x18)) == 0xE981) && !memcmp(epbuff+0x1e,\"\\x8B\\xD5\\x81\\xC2\", 4)) { offset = 0; if (0x6c - cli_readint32(epbuff+0xf) + cli_readint32(epbuff+0x22) == 0xC6) ecx = cli_readint32(epbuff+0x14) - cli_readint32(epbuff+0x1a); } \/* yC 1.3 variant *\/ if (!ecx && !memcmp(epbuff, \"\\x55\\x8B\\xEC\\x83\\xEC\\x40\\x53\\x56\\x57\", 9) && !memcmp(epbuff+0x17, \"\\xe8\\x00\\x00\\x00\\x00\\x5d\\x81\\xed\", 8) && ((uint8_t)epbuff[0x23] == 0xB9)) { offset = 0x10; if (0x6c - cli_readint32(epbuff+0x1f) + cli_readint32(epbuff+0x32) == 0xC6) ecx = cli_readint32(epbuff+0x24) - cli_readint32(epbuff+0x2a); } \/* yC 1.x\/modified *\/ if (!ecx && !memcmp(epbuff, \"\\x60\\xe8\\x00\\x00\\x00\\x00\\x5d\\x81\\xed\",9) && ((uint8_t)epbuff[0xd] == 0xb9) && ((uint16_t)cli_readint16(epbuff + 0x12)== 0xbd8d) && !memcmp(epbuff+0x18, \"\\x8b\\xf7\\xac\", 3)) { offset = -0x18; if (0x66 - cli_readint32(epbuff+0x9) + cli_readint32(epbuff+0x14) == 0xae) ecx = cli_readint32(epbuff+0xe); } if (ecx > 0x800 && ecx < 0x2000 && !memcmp(epbuff+0x63+offset, \"\\xaa\\xe2\\xcc\", 3) && (fsize >= exe_sections[nsections-1].raw + 0xC6 + ecx + offset)) { char *spinned; if((spinned = (char *) cli_malloc(fsize)) == NULL) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) { cli_dbgmsg(\"yC: Can't read %lu bytes\\n\", (unsigned long)fsize); free(spinned); free(exe_sections); return CL_EREAD; } cli_dbgmsg(\"%d,%d,%d,%d\\n\", nsections-1, e_lfanew, ecx, offset); CLI_UNPTEMP(\"yC\",(spinned,exe_sections,0)); CLI_UNPRESULTS(\"yC\",(yc_decrypt(spinned, fsize, exe_sections, nsections-1, e_lfanew, ndesc, ecx, offset)),0,(spinned,0)); } } \/* WWPack *\/ while ((DCONF & PE_CONF_WWPACK) && nsections > 1 && vep == exe_sections[nsections - 1].rva && memcmp(epbuff, \"\\x53\\x55\\x8b\\xe8\\x33\\xdb\\xeb\", 7) == 0 && memcmp(epbuff+0x68, \"\\xe8\\x00\\x00\\x00\\x00\\x58\\x2d\\x6d\\x00\\x00\\x00\\x50\\x60\\x33\\xc9\\x50\\x58\\x50\\x50\", 19) == 0) { uint32_t head = exe_sections[nsections - 1].raw; uint8_t *packer; ssize = 0; for(i=0 ; ; i++) { if(exe_sections[i].rawssize) break; CLI_UNPSIZELIMITS(\"WWPack\", ssize); if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) { free(exe_sections); return CL_EMEM; } if((size_t) fmap_readn(map, src, 0, head) != head) { cli_dbgmsg(\"WWPack: Can't read %d bytes from headers\\n\", head); free(src); free(exe_sections); return CL_EREAD; } for(i = 0 ; i < (unsigned int)nsections-1; i++) { if(!exe_sections[i].rsz) continue; if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break; if(fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break; } if(i+1!=nsections) { cli_dbgmsg(\"WWpack: Probably hacked\/damaged file.\\n\"); free(src); break; } if((packer = (uint8_t *) cli_calloc(exe_sections[nsections - 1].rsz, sizeof(char))) == NULL) { free(src); free(exe_sections); return CL_EMEM; } if(!exe_sections[nsections - 1].rsz || (size_t) fmap_readn(map, packer, exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz) != exe_sections[nsections - 1].rsz) { cli_dbgmsg(\"WWPack: Can't read %d bytes from wwpack sect\\n\", exe_sections[nsections - 1].rsz); free(src); free(packer); free(exe_sections); return CL_EREAD; } CLI_UNPTEMP(\"WWPack\",(src,packer,exe_sections,0)); CLI_UNPRESULTS(\"WWPack\",(wwunpack((uint8_t *)src, ssize, packer, exe_sections, nsections-1, e_lfanew, ndesc)),0,(src,packer,0)); break; } \/* ASPACK support *\/ while((DCONF & PE_CONF_ASPACK) && ep+58+0x70e < fsize && !memcmp(epbuff,\"\\x60\\xe8\\x03\\x00\\x00\\x00\\xe9\\xeb\",8)) { if(epsize<0x3bf || memcmp(epbuff+0x3b9, \"\\x68\\x00\\x00\\x00\\x00\\xc3\",6)) break; ssize = 0; for(i=0 ; i< nsections ; i++) if(ssizecorrupted_input = corrupted_cur; \/* Bytecode BC_PE_UNPACKER hook *\/ bc_ctx = cli_bytecode_context_alloc(); if (!bc_ctx) { cli_errmsg(\"cli_scanpe: can't allocate memory for bc_ctx\\n\"); return CL_EMEM; } cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections); cli_bytecode_context_setctx(bc_ctx, ctx); ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_UNPACKER, map); switch (ret) { case CL_VIRUS: free(exe_sections); cli_bytecode_context_destroy(bc_ctx); return CL_VIRUS; case CL_SUCCESS: ndesc = cli_bytecode_context_getresult_file(bc_ctx, &tempfile); cli_bytecode_context_destroy(bc_ctx); if (ndesc != -1 && tempfile) { CLI_UNPRESULTS(\"bytecode PE hook\", 1, 1, (0)); } break; default: cli_bytecode_context_destroy(bc_ctx); } free(exe_sections); if (SCAN_ALL && viruses_found) return CL_VIRUS; return CL_CLEAN;","output":{"is_vulnerable":"True","vulnerability_types":["Improper Check or Handling of Exceptional Conditions"],"explanation":"Integer underflow in the cli_scanpe function in pe.c in ClamAV before 0.97.8 allows remote attackers to cause a denial of service (crash) via a skewed offset larger than the size of the PE section in a UPX packed executable, which triggers an out-of-bounds read.","severity_level":"Medium","cwe":"CWE-703","cve":"CVE-2013-2020"}} -{"idx":198157,"input":"CallResult Interpreter::interpretFunction( Runtime *runtime, InterpreterState &state) { \/\/ The interepter is re-entrant and also saves\/restores its IP via the runtime \/\/ whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure \/\/ to preserve the IP across calls to interpeterFunction() disrupt interpreter \/\/ calls further up the C++ callstack. The RAII utility class below makes sure \/\/ we always do this correctly. \/\/ \/\/ TODO: The IPs stored in the C++ callstack via this holder will generally be \/\/ the same as in the JS stack frames via the Saved IP field. We can probably \/\/ get rid of one of these redundant stores. Doing this isn't completely \/\/ trivial as there are currently cases where we re-enter the interpreter \/\/ without calling Runtime::saveCallerIPInStackFrame(), and there are features \/\/ (I think mostly the debugger + stack traces) which implicitly rely on \/\/ this behavior. At least their tests break if this behavior is not \/\/ preserved. struct IPSaver { IPSaver(Runtime *runtime) : ip_(runtime->getCurrentIP()), runtime_(runtime) {} ~IPSaver() { runtime_->setCurrentIP(ip_); } private: const Inst *ip_; Runtime *runtime_; }; IPSaver ipSaver(runtime); #ifndef HERMES_ENABLE_DEBUGGER static_assert(!SingleStep, \"can't use single-step mode without the debugger\"); #endif \/\/ Make sure that the cache can use an optimization by avoiding a branch to \/\/ access the property storage. static_assert( HiddenClass::kDictionaryThreshold <= SegmentedArray::kValueToSegmentThreshold, \"Cannot avoid branches in cache check if the dictionary \" \"crossover point is larger than the inline storage\"); CodeBlock *curCodeBlock = state.codeBlock; const Inst *ip = nullptr; \/\/ Holds runtime->currentFrame_.ptr()-1 which is the first local \/\/ register. This eliminates the indirect load from Runtime and the -1 offset. PinnedHermesValue *frameRegs; \/\/ Strictness of current function. bool strictMode; \/\/ Default flags when accessing properties. PropOpFlags defaultPropOpFlags; \/\/ These CAPTURE_IP* macros should wrap around any major calls out of the \/\/ interpeter loop. They stash and retrieve the IP via the current Runtime \/\/ allowing the IP to be externally observed and even altered to change the flow \/\/ of execution. Explicitly saving AND restoring the IP from the Runtime in this \/\/ way means the C++ compiler will keep IP in a register within the rest of the \/\/ interpeter loop. \/\/ \/\/ When assertions are enabled we take the extra step of \"invalidating\" the IP \/\/ between captures so we can detect if it's erroneously accessed. \/\/ \/\/ In some cases we explicitly don't want to invalidate the IP and instead want \/\/ it to stay set. For this we use the *NO_INVALIDATE variants. This comes up \/\/ when we're performing a call operation which may re-enter the interpeter \/\/ loop, and so need the IP available for the saveCallerIPInStackFrame() call \/\/ when we next enter. #define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \\ runtime->setCurrentIP(ip); \\ dst = expr; \\ ip = runtime->getCurrentIP(); #ifdef NDEBUG #define CAPTURE_IP(expr) \\ runtime->setCurrentIP(ip); \\ (void)expr; \\ ip = runtime->getCurrentIP(); #define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) #else \/\/ !NDEBUG #define CAPTURE_IP(expr) \\ runtime->setCurrentIP(ip); \\ (void)expr; \\ ip = runtime->getCurrentIP(); \\ runtime->invalidateCurrentIP(); #define CAPTURE_IP_ASSIGN(dst, expr) \\ runtime->setCurrentIP(ip); \\ dst = expr; \\ ip = runtime->getCurrentIP(); \\ runtime->invalidateCurrentIP(); #endif \/\/ NDEBUG LLVM_DEBUG(dbgs() << \"interpretFunction() called\\n\"); ScopedNativeDepthTracker depthTracker{runtime}; if (LLVM_UNLIKELY(depthTracker.overflowed())) { return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack); } if (!SingleStep) { if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) { return (*jitPtr)(runtime); } } GCScope gcScope(runtime); \/\/ Avoid allocating a handle dynamically by reusing this one. MutableHandle<> tmpHandle(runtime); CallResult res{ExecutionStatus::EXCEPTION}; CallResult> resPH{ExecutionStatus::EXCEPTION}; CallResult> resArgs{ExecutionStatus::EXCEPTION}; CallResult boolRes{ExecutionStatus::EXCEPTION}; \/\/ Mark the gcScope so we can clear all allocated handles. \/\/ Remember how many handles the scope has so we can clear them in the loop. static constexpr unsigned KEEP_HANDLES = 1; assert( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"scope has unexpected number of handles\"); INIT_OPCODE_PROFILER; #if !defined(HERMESVM_PROFILER_EXTERN) tailCall: #endif PROFILER_ENTER_FUNCTION(curCodeBlock); #ifdef HERMES_ENABLE_DEBUGGER runtime->getDebugger().willEnterCodeBlock(curCodeBlock); #endif runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock); \/\/ Update function executionCount_ count curCodeBlock->incrementExecutionCount(); if (!SingleStep) { auto newFrame = runtime->setCurrentFrameToTopOfStack(); runtime->saveCallerIPInStackFrame(); #ifndef NDEBUG runtime->invalidateCurrentIP(); #endif \/\/ Point frameRegs to the first register in the new frame. Note that at this \/\/ moment technically it points above the top of the stack, but we are never \/\/ going to access it. frameRegs = &newFrame.getFirstLocalRef(); #ifndef NDEBUG LLVM_DEBUG( dbgs() << \"function entry: stackLevel=\" << runtime->getStackLevel() << \", argCount=\" << runtime->getCurrentFrame().getArgCount() << \", frameSize=\" << curCodeBlock->getFrameSize() << \"\\n\"); LLVM_DEBUG( dbgs() << \" callee \" << DumpHermesValue( runtime->getCurrentFrame().getCalleeClosureOrCBRef()) << \"\\n\"); LLVM_DEBUG( dbgs() << \" this \" << DumpHermesValue(runtime->getCurrentFrame().getThisArgRef()) << \"\\n\"); for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) { LLVM_DEBUG( dbgs() << \" \" << llvh::format_decimal(i, 4) << \" \" << DumpHermesValue(runtime->getCurrentFrame().getArgRef(i)) << \"\\n\"); } #endif \/\/ Allocate the registers for the new frame. if (LLVM_UNLIKELY(!runtime->checkAndAllocStack( curCodeBlock->getFrameSize() + StackFrameLayout::CalleeExtraRegistersAtStart, HermesValue::encodeUndefinedValue()))) goto stackOverflow; ip = (Inst const *)curCodeBlock->begin(); \/\/ Check for invalid invocation. if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited( newFrame.isConstructorCall()))) { if (!newFrame.isConstructorCall()) { CAPTURE_IP( runtime->raiseTypeError(\"Class constructor invoked without new\")); } else { CAPTURE_IP(runtime->raiseTypeError(\"Function is not a constructor\")); } goto handleExceptionInParent; } } else { \/\/ Point frameRegs to the first register in the frame. frameRegs = &runtime->getCurrentFrame().getFirstLocalRef(); ip = (Inst const *)(curCodeBlock->begin() + state.offset); } assert((const uint8_t *)ip < curCodeBlock->end() && \"CodeBlock is empty\"); INIT_STATE_FOR_CODEBLOCK(curCodeBlock); #define BEFORE_OP_CODE \\ { \\ UPDATE_OPCODE_TIME_SPENT; \\ HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \\ HERMES_SLOW_ASSERT( \\ gcScope.getHandleCountDbg() == KEEP_HANDLES && \\ \"unaccounted handles were created\"); \\ HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && \"tmpHandle not cleared\"); \\ RECORD_OPCODE_START_TIME; \\ INC_OPCODE_COUNT; \\ } #ifdef HERMESVM_INDIRECT_THREADING static void *opcodeDispatch[] = { #define DEFINE_OPCODE(name) &&case_##name, #include \"hermes\/BCGen\/HBC\/BytecodeList.def\" &&case__last}; #define CASE(name) case_##name: #define DISPATCH \\ BEFORE_OP_CODE; \\ if (SingleStep) { \\ state.codeBlock = curCodeBlock; \\ state.offset = CUROFFSET; \\ return HermesValue::encodeUndefinedValue(); \\ } \\ goto *opcodeDispatch[(unsigned)ip->opCode] #else \/\/ HERMESVM_INDIRECT_THREADING #define CASE(name) case OpCode::name: #define DISPATCH \\ if (SingleStep) { \\ state.codeBlock = curCodeBlock; \\ state.offset = CUROFFSET; \\ return HermesValue::encodeUndefinedValue(); \\ } \\ continue #endif \/\/ HERMESVM_INDIRECT_THREADING #define RUN_DEBUGGER_ASYNC_BREAK(flags) \\ do { \\ CAPTURE_IP_ASSIGN( \\ auto dRes, \\ runDebuggerUpdatingState( \\ (uint8_t)(flags) & \\ (uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \\ ? Debugger::RunReason::AsyncBreakExplicit \\ : Debugger::RunReason::AsyncBreakImplicit, \\ runtime, \\ curCodeBlock, \\ ip, \\ frameRegs)); \\ if (dRes == ExecutionStatus::EXCEPTION) \\ goto exception; \\ } while (0) for (;;) { BEFORE_OP_CODE; #ifdef HERMESVM_INDIRECT_THREADING goto *opcodeDispatch[(unsigned)ip->opCode]; #else switch (ip->opCode) #endif { const Inst *nextIP; uint32_t idVal; bool tryProp; uint32_t callArgCount; \/\/ This is HermesValue::getRaw(), since HermesValue cannot be assigned \/\/ to. It is meant to be used only for very short durations, in the \/\/ dispatch of call instructions, when there is definitely no possibility \/\/ of a GC. HermesValue::RawType callNewTarget; \/\/\/ Handle an opcode \\p name with an out-of-line implementation in a function \/\/\/ ExecutionStatus caseName( \/\/\/ Runtime *, \/\/\/ PinnedHermesValue *frameRegs, \/\/\/ Inst *ip) #define CASE_OUTOFLINE(name) \\ CASE(name) { \\ CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \\ if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \\ goto exception; \\ } \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a binary arithmetic instruction with a fast path where both \/\/\/ operands are numbers. \/\/\/ \\param name the name of the instruction. The fast path case will have a \/\/\/ \"n\" appended to the name. \/\/\/ \\param oper the C++ operator to use to actually perform the arithmetic \/\/\/ operation. #define BINOP(name, oper) \\ CASE(name) { \\ if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\ \/* Fast-path. *\/ \\ CASE(name##N) { \\ O1REG(name) = HermesValue::encodeDoubleValue( \\ oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \\ } \\ CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) \\ goto exception; \\ double left = res->getDouble(); \\ CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) \\ goto exception; \\ O1REG(name) = \\ HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a shift instruction with a fast path where both \/\/\/ operands are numbers. \/\/\/ \\param name the name of the instruction. \/\/\/ \\param oper the C++ operator to use to actually perform the shift \/\/\/ operation. \/\/\/ \\param lConv the conversion function for the LHS of the expression. \/\/\/ \\param lType the type of the LHS operand. \/\/\/ \\param returnType the type of the return value. #define SHIFTOP(name, oper, lConv, lType, returnType) \\ CASE(name) { \\ if (LLVM_LIKELY( \\ O2REG(name).isNumber() && \\ O3REG(name).isNumber())) { \/* Fast-path. *\/ \\ auto lnum = static_cast( \\ hermes::truncateToInt32(O2REG(name).getNumber())); \\ auto rnum = static_cast( \\ hermes::truncateToInt32(O3REG(name).getNumber())) & \\ 0x1f; \\ O1REG(name) = HermesValue::encodeDoubleValue( \\ static_cast(lnum oper rnum)); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \\ CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ auto lnum = static_cast(res->getNumber()); \\ CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ auto rnum = static_cast(res->getNumber()) & 0x1f; \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ O1REG(name) = HermesValue::encodeDoubleValue( \\ static_cast(lnum oper rnum)); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a binary bitwise instruction with a fast path where both \/\/\/ operands are numbers. \/\/\/ \\param name the name of the instruction. \/\/\/ \\param oper the C++ operator to use to actually perform the bitwise \/\/\/ operation. #define BITWISEBINOP(name, oper) \\ CASE(name) { \\ if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\ \/* Fast-path. *\/ \\ O1REG(name) = HermesValue::encodeDoubleValue( \\ hermes::truncateToInt32(O2REG(name).getNumber()) \\ oper hermes::truncateToInt32(O3REG(name).getNumber())); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \\ CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ int32_t left = res->getNumberAs(); \\ CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ O1REG(name) = \\ HermesValue::encodeNumberValue(left oper res->getNumberAs()); \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a comparison instruction. \/\/\/ \\param name the name of the instruction. \/\/\/ \\param oper the C++ operator to use to actually perform the fast arithmetic \/\/\/ comparison. \/\/\/ \\param operFuncName function to call for the slow-path comparison. #define CONDOP(name, oper, operFuncName) \\ CASE(name) { \\ if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\ \/* Fast-path. *\/ \\ O1REG(name) = HermesValue::encodeBoolValue( \\ O2REG(name).getNumber() oper O3REG(name).getNumber()); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \\ CAPTURE_IP_ASSIGN( \\ boolRes, \\ operFuncName( \\ runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \\ if (boolRes == ExecutionStatus::EXCEPTION) \\ goto exception; \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } \/\/\/ Implement a comparison conditional jump with a fast path where both \/\/\/ operands are numbers. \/\/\/ \\param name the name of the instruction. The fast path case will have a \/\/\/ \"N\" appended to the name. \/\/\/ \\param suffix Optional suffix to be added to the end (e.g. Long) \/\/\/ \\param oper the C++ operator to use to actually perform the fast arithmetic \/\/\/ comparison. \/\/\/ \\param operFuncName function to call for the slow-path comparison. \/\/\/ \\param trueDest ip value if the conditional evaluates to true \/\/\/ \\param falseDest ip value if the conditional evaluates to false #define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \\ CASE(name##suffix) { \\ if (LLVM_LIKELY( \\ O2REG(name##suffix).isNumber() && \\ O3REG(name##suffix).isNumber())) { \\ \/* Fast-path. *\/ \\ CASE(name##N##suffix) { \\ if (O2REG(name##N##suffix) \\ .getNumber() oper O3REG(name##N##suffix) \\ .getNumber()) { \\ ip = trueDest; \\ DISPATCH; \\ } \\ ip = falseDest; \\ DISPATCH; \\ } \\ } \\ CAPTURE_IP_ASSIGN( \\ boolRes, \\ operFuncName( \\ runtime, \\ Handle<>(&O2REG(name##suffix)), \\ Handle<>(&O3REG(name##suffix)))); \\ if (boolRes == ExecutionStatus::EXCEPTION) \\ goto exception; \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ if (boolRes.getValue()) { \\ ip = trueDest; \\ DISPATCH; \\ } \\ ip = falseDest; \\ DISPATCH; \\ } \/\/\/ Implement a strict equality conditional jump \/\/\/ \\param name the name of the instruction. \/\/\/ \\param suffix Optional suffix to be added to the end (e.g. Long) \/\/\/ \\param trueDest ip value if the conditional evaluates to true \/\/\/ \\param falseDest ip value if the conditional evaluates to false #define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \\ CASE(name##suffix) { \\ if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \\ ip = trueDest; \\ DISPATCH; \\ } \\ ip = falseDest; \\ DISPATCH; \\ } \/\/\/ Implement an equality conditional jump \/\/\/ \\param name the name of the instruction. \/\/\/ \\param suffix Optional suffix to be added to the end (e.g. Long) \/\/\/ \\param trueDest ip value if the conditional evaluates to true \/\/\/ \\param falseDest ip value if the conditional evaluates to false #define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \\ CASE(name##suffix) { \\ CAPTURE_IP_ASSIGN( \\ res, \\ abstractEqualityTest_RJS( \\ runtime, \\ Handle<>(&O2REG(name##suffix)), \\ Handle<>(&O3REG(name##suffix)))); \\ if (res == ExecutionStatus::EXCEPTION) { \\ goto exception; \\ } \\ gcScope.flushToSmallCount(KEEP_HANDLES); \\ if (res->getBool()) { \\ ip = trueDest; \\ DISPATCH; \\ } \\ ip = falseDest; \\ DISPATCH; \\ } \/\/\/ Implement the long and short forms of a conditional jump, and its negation. #define JCOND(name, oper, operFuncName) \\ JCOND_IMPL( \\ J##name, \\ , \\ oper, \\ operFuncName, \\ IPADD(ip->iJ##name.op1), \\ NEXTINST(J##name)); \\ JCOND_IMPL( \\ J##name, \\ Long, \\ oper, \\ operFuncName, \\ IPADD(ip->iJ##name##Long.op1), \\ NEXTINST(J##name##Long)); \\ JCOND_IMPL( \\ JNot##name, \\ , \\ oper, \\ operFuncName, \\ NEXTINST(JNot##name), \\ IPADD(ip->iJNot##name.op1)); \\ JCOND_IMPL( \\ JNot##name, \\ Long, \\ oper, \\ operFuncName, \\ NEXTINST(JNot##name##Long), \\ IPADD(ip->iJNot##name##Long.op1)); \/\/\/ Load a constant. \/\/\/ \\param value is the value to store in the output register. #define LOAD_CONST(name, value) \\ CASE(name) { \\ O1REG(name) = value; \\ ip = NEXTINST(name); \\ DISPATCH; \\ } #define LOAD_CONST_CAPTURE_IP(name, value) \\ CASE(name) { \\ CAPTURE_IP_ASSIGN(O1REG(name), value); \\ ip = NEXTINST(name); \\ DISPATCH; \\ } CASE(Mov) { O1REG(Mov) = O2REG(Mov); ip = NEXTINST(Mov); DISPATCH; } CASE(MovLong) { O1REG(MovLong) = O2REG(MovLong); ip = NEXTINST(MovLong); DISPATCH; } CASE(LoadParam) { if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) { \/\/ index 0 must load 'this'. Index 1 the first argument, etc. O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1); ip = NEXTINST(LoadParam); DISPATCH; } O1REG(LoadParam) = HermesValue::encodeUndefinedValue(); ip = NEXTINST(LoadParam); DISPATCH; } CASE(LoadParamLong) { if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) { \/\/ index 0 must load 'this'. Index 1 the first argument, etc. O1REG(LoadParamLong) = FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1); ip = NEXTINST(LoadParamLong); DISPATCH; } O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue(); ip = NEXTINST(LoadParamLong); DISPATCH; } CASE(CoerceThisNS) { if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) { O1REG(CoerceThisNS) = O2REG(CoerceThisNS); } else if ( O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) { O1REG(CoerceThisNS) = runtime->global_; } else { tmpHandle = O2REG(CoerceThisNS); nextIP = NEXTINST(CoerceThisNS); goto coerceThisSlowPath; } ip = NEXTINST(CoerceThisNS); DISPATCH; } CASE(LoadThisNS) { if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) { O1REG(LoadThisNS) = FRAME.getThisArgRef(); } else if ( FRAME.getThisArgRef().isNull() || FRAME.getThisArgRef().isUndefined()) { O1REG(LoadThisNS) = runtime->global_; } else { tmpHandle = FRAME.getThisArgRef(); nextIP = NEXTINST(LoadThisNS); goto coerceThisSlowPath; } ip = NEXTINST(LoadThisNS); DISPATCH; } coerceThisSlowPath : { CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle)); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CoerceThisNS) = res.getValue(); tmpHandle.clear(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(ConstructLong) { callArgCount = (uint32_t)ip->iConstructLong.op3; nextIP = NEXTINST(ConstructLong); callNewTarget = O2REG(ConstructLong).getRaw(); goto doCall; } CASE(CallLong) { callArgCount = (uint32_t)ip->iCallLong.op3; nextIP = NEXTINST(CallLong); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } \/\/ Note in Call1 through Call4, the first argument is 'this' which has \/\/ argument index -1. \/\/ Also note that we are writing to callNewTarget last, to avoid the \/\/ possibility of it being aliased by the arg writes. CASE(Call1) { callArgCount = 1; nextIP = NEXTINST(Call1); StackFramePtr fr{runtime->stackPointer_}; fr.getArgRefUnsafe(-1) = O3REG(Call1); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } CASE(Call2) { callArgCount = 2; nextIP = NEXTINST(Call2); StackFramePtr fr{runtime->stackPointer_}; fr.getArgRefUnsafe(-1) = O3REG(Call2); fr.getArgRefUnsafe(0) = O4REG(Call2); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } CASE(Call3) { callArgCount = 3; nextIP = NEXTINST(Call3); StackFramePtr fr{runtime->stackPointer_}; fr.getArgRefUnsafe(-1) = O3REG(Call3); fr.getArgRefUnsafe(0) = O4REG(Call3); fr.getArgRefUnsafe(1) = O5REG(Call3); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } CASE(Call4) { callArgCount = 4; nextIP = NEXTINST(Call4); StackFramePtr fr{runtime->stackPointer_}; fr.getArgRefUnsafe(-1) = O3REG(Call4); fr.getArgRefUnsafe(0) = O4REG(Call4); fr.getArgRefUnsafe(1) = O5REG(Call4); fr.getArgRefUnsafe(2) = O6REG(Call4); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); goto doCall; } CASE(Construct) { callArgCount = (uint32_t)ip->iConstruct.op3; nextIP = NEXTINST(Construct); callNewTarget = O2REG(Construct).getRaw(); goto doCall; } CASE(Call) { callArgCount = (uint32_t)ip->iCall.op3; nextIP = NEXTINST(Call); callNewTarget = HermesValue::encodeUndefinedValue().getRaw(); \/\/ Fall through. } doCall : { #ifdef HERMES_ENABLE_DEBUGGER \/\/ Check for an async debugger request. if (uint8_t asyncFlags = runtime->testAndClearDebuggerAsyncBreakRequest()) { RUN_DEBUGGER_ASYNC_BREAK(asyncFlags); gcScope.flushToSmallCount(KEEP_HANDLES); DISPATCH; } #endif \/\/ Subtract 1 from callArgCount as 'this' is considered an argument in the \/\/ instruction, but not in the frame. CAPTURE_IP_ASSIGN_NO_INVALIDATE( auto newFrame, StackFramePtr::initFrame( runtime->stackPointer_, FRAME, ip, curCodeBlock, callArgCount - 1, O2REG(Call), HermesValue::fromRaw(callNewTarget))); (void)newFrame; SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame)); if (auto *func = dyn_vmcast(O2REG(Call))) { assert(!SingleStep && \"can't single-step a call\"); #ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES runtime->pushCallStack(curCodeBlock, ip); #endif CodeBlock *calleeBlock = func->getCodeBlock(); calleeBlock->lazyCompile(runtime); #if defined(HERMESVM_PROFILER_EXTERN) CAPTURE_IP_ASSIGN_NO_INVALIDATE( res, runtime->interpretFunction(calleeBlock)); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(Call) = *res; gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; #else if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) { res = (*jitPtr)(runtime); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) goto exception; O1REG(Call) = *res; SLOW_DEBUG( dbgs() << \"JIT return value r\" << (unsigned)ip->iCall.op1 << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\"); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } curCodeBlock = calleeBlock; goto tailCall; #endif } CAPTURE_IP_ASSIGN_NO_INVALIDATE( resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call))); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(Call) = std::move(resPH->get()); SLOW_DEBUG( dbgs() << \"native return value r\" << (unsigned)ip->iCall.op1 << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\"); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(CallDirect) CASE(CallDirectLongIndex) { #ifdef HERMES_ENABLE_DEBUGGER \/\/ Check for an async debugger request. if (uint8_t asyncFlags = runtime->testAndClearDebuggerAsyncBreakRequest()) { RUN_DEBUGGER_ASYNC_BREAK(asyncFlags); gcScope.flushToSmallCount(KEEP_HANDLES); DISPATCH; } #endif CAPTURE_IP_ASSIGN( CodeBlock * calleeBlock, ip->opCode == OpCode::CallDirect ? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate( ip->iCallDirect.op3) : curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate( ip->iCallDirectLongIndex.op3)); CAPTURE_IP_ASSIGN_NO_INVALIDATE( auto newFrame, StackFramePtr::initFrame( runtime->stackPointer_, FRAME, ip, curCodeBlock, (uint32_t)ip->iCallDirect.op2 - 1, HermesValue::encodeNativePointer(calleeBlock), HermesValue::encodeUndefinedValue())); (void)newFrame; LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame)); assert(!SingleStep && \"can't single-step a call\"); calleeBlock->lazyCompile(runtime); #if defined(HERMESVM_PROFILER_EXTERN) CAPTURE_IP_ASSIGN_NO_INVALIDATE( res, runtime->interpretFunction(calleeBlock)); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CallDirect) = *res; gcScope.flushToSmallCount(KEEP_HANDLES); ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect) : NEXTINST(CallDirectLongIndex); DISPATCH; #else if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) { res = (*jitPtr)(runtime); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) goto exception; O1REG(CallDirect) = *res; LLVM_DEBUG( dbgs() << \"JIT return value r\" << (unsigned)ip->iCallDirect.op1 << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\"); gcScope.flushToSmallCount(KEEP_HANDLES); ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect) : NEXTINST(CallDirectLongIndex); DISPATCH; } curCodeBlock = calleeBlock; goto tailCall; #endif } CASE(CallBuiltin) { NativeFunction *nf = runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2); CAPTURE_IP_ASSIGN( auto newFrame, StackFramePtr::initFrame( runtime->stackPointer_, FRAME, ip, curCodeBlock, (uint32_t)ip->iCallBuiltin.op3 - 1, nf, false)); \/\/ \"thisArg\" is implicitly assumed to \"undefined\". newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue(); SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame)); CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) goto exception; O1REG(CallBuiltin) = std::move(resPH->get()); SLOW_DEBUG( dbgs() << \"native return value r\" << (unsigned)ip->iCallBuiltin.op1 << \"=\" << DumpHermesValue(O1REG(CallBuiltin)) << \"\\n\"); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CallBuiltin); DISPATCH; } CASE(CompleteGenerator) { auto *innerFn = vmcast( runtime->getCurrentFrame().getCalleeClosure()); innerFn->setState(GeneratorInnerFunction::State::Completed); ip = NEXTINST(CompleteGenerator); DISPATCH; } CASE(SaveGenerator) { nextIP = IPADD(ip->iSaveGenerator.op1); goto doSaveGen; } CASE(SaveGeneratorLong) { nextIP = IPADD(ip->iSaveGeneratorLong.op1); goto doSaveGen; } doSaveGen : { auto *innerFn = vmcast( runtime->getCurrentFrame().getCalleeClosure()); innerFn->saveStack(runtime); innerFn->setNextIP(nextIP); innerFn->setState(GeneratorInnerFunction::State::SuspendedYield); ip = NEXTINST(SaveGenerator); DISPATCH; } CASE(StartGenerator) { auto *innerFn = vmcast( runtime->getCurrentFrame().getCalleeClosure()); if (innerFn->getState() == GeneratorInnerFunction::State::SuspendedStart) { nextIP = NEXTINST(StartGenerator); } else { nextIP = innerFn->getNextIP(); innerFn->restoreStack(runtime); } innerFn->setState(GeneratorInnerFunction::State::Executing); ip = nextIP; DISPATCH; } CASE(ResumeGenerator) { auto *innerFn = vmcast( runtime->getCurrentFrame().getCalleeClosure()); O1REG(ResumeGenerator) = innerFn->getResult(); O2REG(ResumeGenerator) = HermesValue::encodeBoolValue( innerFn->getAction() == GeneratorInnerFunction::Action::Return); innerFn->clearResult(runtime); if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) { runtime->setThrownValue(O1REG(ResumeGenerator)); goto exception; } ip = NEXTINST(ResumeGenerator); DISPATCH; } CASE(Ret) { #ifdef HERMES_ENABLE_DEBUGGER \/\/ Check for an async debugger request. if (uint8_t asyncFlags = runtime->testAndClearDebuggerAsyncBreakRequest()) { RUN_DEBUGGER_ASYNC_BREAK(asyncFlags); gcScope.flushToSmallCount(KEEP_HANDLES); DISPATCH; } #endif PROFILER_EXIT_FUNCTION(curCodeBlock); #ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES runtime->popCallStack(); #endif \/\/ Store the return value. res = O1REG(Ret); ip = FRAME.getSavedIP(); curCodeBlock = FRAME.getSavedCodeBlock(); frameRegs = &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef(); SLOW_DEBUG( dbgs() << \"function exit: restored stackLevel=\" << runtime->getStackLevel() << \"\\n\"); \/\/ Are we returning to native code? if (!curCodeBlock) { SLOW_DEBUG(dbgs() << \"function exit: returning to native code\\n\"); return res; } \/\/ Return because of recursive calling structure #if defined(HERMESVM_PROFILER_EXTERN) return res; #endif INIT_STATE_FOR_CODEBLOCK(curCodeBlock); O1REG(Call) = res.getValue(); ip = nextInstCall(ip); DISPATCH; } CASE(Catch) { assert(!runtime->thrownValue_.isEmpty() && \"Invalid thrown value\"); assert( !isUncatchableError(runtime->thrownValue_) && \"Uncatchable thrown value was caught\"); O1REG(Catch) = runtime->thrownValue_; runtime->clearThrownValue(); #ifdef HERMES_ENABLE_DEBUGGER \/\/ Signal to the debugger that we're done unwinding an exception, \/\/ and we can resume normal debugging flow. runtime->debugger_.finishedUnwindingException(); #endif ip = NEXTINST(Catch); DISPATCH; } CASE(Throw) { runtime->thrownValue_ = O1REG(Throw); SLOW_DEBUG( dbgs() << \"Exception thrown: \" << DumpHermesValue(runtime->thrownValue_) << \"\\n\"); goto exception; } CASE(ThrowIfUndefinedInst) { if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) { SLOW_DEBUG( dbgs() << \"Throwing ReferenceError for undefined variable\"); CAPTURE_IP(runtime->raiseReferenceError( \"accessing an uninitialized variable\")); goto exception; } ip = NEXTINST(ThrowIfUndefinedInst); DISPATCH; } CASE(Debugger) { SLOW_DEBUG(dbgs() << \"debugger statement executed\\n\"); #ifdef HERMES_ENABLE_DEBUGGER { if (!runtime->debugger_.isDebugging()) { \/\/ Only run the debugger if we're not already debugging. \/\/ Don't want to call it again and mess with its state. CAPTURE_IP_ASSIGN( auto res, runDebuggerUpdatingState( Debugger::RunReason::Opcode, runtime, curCodeBlock, ip, frameRegs)); if (res == ExecutionStatus::EXCEPTION) { \/\/ If one of the internal steps threw, \/\/ then handle that here by jumping to where we're supposed to go. \/\/ If we're in mid-step, the breakpoint at the catch point \/\/ will have been set by the debugger. \/\/ We don't want to execute this instruction because it's already \/\/ thrown. goto exception; } } auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip); if (breakpointOpt.hasValue()) { \/\/ We're on a breakpoint but we're supposed to continue. curCodeBlock->uninstallBreakpointAtOffset( CUROFFSET, breakpointOpt->opCode); if (ip->opCode == OpCode::Debugger) { \/\/ Breakpointed a debugger instruction, so move past it \/\/ since we've already called the debugger on this instruction. ip = NEXTINST(Debugger); } else { InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET}; CAPTURE_IP_ASSIGN( ExecutionStatus status, runtime->stepFunction(newState)); curCodeBlock->installBreakpointAtOffset(CUROFFSET); if (status == ExecutionStatus::EXCEPTION) { goto exception; } curCodeBlock = newState.codeBlock; ip = newState.codeBlock->getOffsetPtr(newState.offset); INIT_STATE_FOR_CODEBLOCK(curCodeBlock); \/\/ Single-stepping should handle call stack management for us. frameRegs = &runtime->getCurrentFrame().getFirstLocalRef(); } } else if (ip->opCode == OpCode::Debugger) { \/\/ No breakpoint here and we've already run the debugger, \/\/ just continue on. \/\/ If the current instruction is no longer a debugger instruction, \/\/ we're just going to keep executing from the current IP. ip = NEXTINST(Debugger); } gcScope.flushToSmallCount(KEEP_HANDLES); } DISPATCH; #else ip = NEXTINST(Debugger); DISPATCH; #endif } CASE(AsyncBreakCheck) { if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) { #ifdef HERMES_ENABLE_DEBUGGER if (uint8_t asyncFlags = runtime->testAndClearDebuggerAsyncBreakRequest()) { RUN_DEBUGGER_ASYNC_BREAK(asyncFlags); } #endif if (runtime->testAndClearTimeoutAsyncBreakRequest()) { CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout()); if (nRes == ExecutionStatus::EXCEPTION) { goto exception; } } } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(AsyncBreakCheck); DISPATCH; } CASE(ProfilePoint) { #ifdef HERMESVM_PROFILER_BB auto pointIndex = ip->iProfilePoint.op1; SLOW_DEBUG(llvh::dbgs() << \"ProfilePoint: \" << pointIndex << \"\\n\"); CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock( curCodeBlock, pointIndex)); #endif ip = NEXTINST(ProfilePoint); DISPATCH; } CASE(Unreachable) { llvm_unreachable(\"Hermes bug: unreachable instruction\"); } CASE(CreateClosure) { idVal = ip->iCreateClosure.op3; nextIP = NEXTINST(CreateClosure); goto createClosure; } CASE(CreateClosureLongIndex) { idVal = ip->iCreateClosureLongIndex.op3; nextIP = NEXTINST(CreateClosureLongIndex); goto createClosure; } createClosure : { auto *runtimeModule = curCodeBlock->getRuntimeModule(); CAPTURE_IP_ASSIGN( O1REG(CreateClosure), JSFunction::create( runtime, runtimeModule->getDomain(runtime), Handle::vmcast(&runtime->functionPrototype), Handle::vmcast(&O2REG(CreateClosure)), runtimeModule->getCodeBlockMayAllocate(idVal)) .getHermesValue()); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(CreateGeneratorClosure) { CAPTURE_IP_ASSIGN( auto res, createGeneratorClosure( runtime, curCodeBlock->getRuntimeModule(), ip->iCreateClosure.op3, Handle::vmcast(&O2REG(CreateGeneratorClosure)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CreateGeneratorClosure) = res->getHermesValue(); res->invalidate(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateGeneratorClosure); DISPATCH; } CASE(CreateGeneratorClosureLongIndex) { CAPTURE_IP_ASSIGN( auto res, createGeneratorClosure( runtime, curCodeBlock->getRuntimeModule(), ip->iCreateClosureLongIndex.op3, Handle::vmcast( &O2REG(CreateGeneratorClosureLongIndex)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue(); res->invalidate(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateGeneratorClosureLongIndex); DISPATCH; } CASE(CreateGenerator) { CAPTURE_IP_ASSIGN( auto res, createGenerator_RJS( runtime, curCodeBlock->getRuntimeModule(), ip->iCreateGenerator.op3, Handle::vmcast(&O2REG(CreateGenerator)), FRAME.getNativeArgs())); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CreateGenerator) = res->getHermesValue(); res->invalidate(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateGenerator); DISPATCH; } CASE(CreateGeneratorLongIndex) { CAPTURE_IP_ASSIGN( auto res, createGenerator_RJS( runtime, curCodeBlock->getRuntimeModule(), ip->iCreateGeneratorLongIndex.op3, Handle::vmcast(&O2REG(CreateGeneratorLongIndex)), FRAME.getNativeArgs())); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(CreateGeneratorLongIndex) = res->getHermesValue(); res->invalidate(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateGeneratorLongIndex); DISPATCH; } CASE(GetEnvironment) { \/\/ The currently executing function must exist, so get the environment. Environment *curEnv = FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime); for (unsigned level = ip->iGetEnvironment.op2; level; --level) { assert(curEnv && \"invalid environment relative level\"); curEnv = curEnv->getParentEnvironment(runtime); } O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv); ip = NEXTINST(GetEnvironment); DISPATCH; } CASE(CreateEnvironment) { tmpHandle = HermesValue::encodeObjectValue( FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime)); CAPTURE_IP_ASSIGN( res, Environment::create( runtime, tmpHandle->getPointer() ? Handle::vmcast(tmpHandle) : Handle::vmcast_or_null( &runtime->nullPointer_), curCodeBlock->getEnvironmentSize())); if (res == ExecutionStatus::EXCEPTION) { goto exception; } O1REG(CreateEnvironment) = *res; #ifdef HERMES_ENABLE_DEBUGGER FRAME.getDebugEnvironmentRef() = *res; #endif tmpHandle = HermesValue::encodeUndefinedValue(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateEnvironment); DISPATCH; } CASE(StoreToEnvironment) { vmcast(O1REG(StoreToEnvironment)) ->slot(ip->iStoreToEnvironment.op2) .set(O3REG(StoreToEnvironment), &runtime->getHeap()); ip = NEXTINST(StoreToEnvironment); DISPATCH; } CASE(StoreToEnvironmentL) { vmcast(O1REG(StoreToEnvironmentL)) ->slot(ip->iStoreToEnvironmentL.op2) .set(O3REG(StoreToEnvironmentL), &runtime->getHeap()); ip = NEXTINST(StoreToEnvironmentL); DISPATCH; } CASE(StoreNPToEnvironment) { vmcast(O1REG(StoreNPToEnvironment)) ->slot(ip->iStoreNPToEnvironment.op2) .setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap()); ip = NEXTINST(StoreNPToEnvironment); DISPATCH; } CASE(StoreNPToEnvironmentL) { vmcast(O1REG(StoreNPToEnvironmentL)) ->slot(ip->iStoreNPToEnvironmentL.op2) .setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap()); ip = NEXTINST(StoreNPToEnvironmentL); DISPATCH; } CASE(LoadFromEnvironment) { O1REG(LoadFromEnvironment) = vmcast(O2REG(LoadFromEnvironment)) ->slot(ip->iLoadFromEnvironment.op3); ip = NEXTINST(LoadFromEnvironment); DISPATCH; } CASE(LoadFromEnvironmentL) { O1REG(LoadFromEnvironmentL) = vmcast(O2REG(LoadFromEnvironmentL)) ->slot(ip->iLoadFromEnvironmentL.op3); ip = NEXTINST(LoadFromEnvironmentL); DISPATCH; } CASE(GetGlobalObject) { O1REG(GetGlobalObject) = runtime->global_; ip = NEXTINST(GetGlobalObject); DISPATCH; } CASE(GetNewTarget) { O1REG(GetNewTarget) = FRAME.getNewTargetRef(); ip = NEXTINST(GetNewTarget); DISPATCH; } CASE(DeclareGlobalVar) { DefinePropertyFlags dpf = DefinePropertyFlags::getDefaultNewPropertyFlags(); dpf.configurable = 0; \/\/ Do not overwrite existing globals with undefined. dpf.setValue = 0; CAPTURE_IP_ASSIGN( auto res, JSObject::defineOwnProperty( runtime->getGlobal(), runtime, ID(ip->iDeclareGlobalVar.op1), dpf, Runtime::getUndefinedValue(), PropOpFlags().plusThrowOnError())); if (res == ExecutionStatus::EXCEPTION) { assert( !runtime->getGlobal()->isProxyObject() && \"global can't be a proxy object\"); \/\/ If the property already exists, this should be a noop. \/\/ Instead of incurring the cost to check every time, do it \/\/ only if an exception is thrown, and swallow the exception \/\/ if it exists, since we didn't want to make the call, \/\/ anyway. This most likely means the property is \/\/ non-configurable. NamedPropertyDescriptor desc; CAPTURE_IP_ASSIGN( auto res, JSObject::getOwnNamedDescriptor( runtime->getGlobal(), runtime, ID(ip->iDeclareGlobalVar.op1), desc)); if (!res) { goto exception; } else { runtime->clearThrownValue(); } \/\/ fall through } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(DeclareGlobalVar); DISPATCH; } CASE(TryGetByIdLong) { tryProp = true; idVal = ip->iTryGetByIdLong.op4; nextIP = NEXTINST(TryGetByIdLong); goto getById; } CASE(GetByIdLong) { tryProp = false; idVal = ip->iGetByIdLong.op4; nextIP = NEXTINST(GetByIdLong); goto getById; } CASE(GetByIdShort) { tryProp = false; idVal = ip->iGetByIdShort.op4; nextIP = NEXTINST(GetByIdShort); goto getById; } CASE(TryGetById) { tryProp = true; idVal = ip->iTryGetById.op4; nextIP = NEXTINST(TryGetById); goto getById; } CASE(GetById) { tryProp = false; idVal = ip->iGetById.op4; nextIP = NEXTINST(GetById); } getById : { ++NumGetById; \/\/ NOTE: it is safe to use OnREG(GetById) here because all instructions \/\/ have the same layout: opcode, registers, non-register operands, i.e. \/\/ they only differ in the width of the last \"identifier\" field. CallResult propRes{ExecutionStatus::EXCEPTION}; if (LLVM_LIKELY(O2REG(GetById).isObject())) { auto *obj = vmcast(O2REG(GetById)); auto cacheIdx = ip->iGetById.op3; auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx); #ifdef HERMESVM_PROFILER_BB { HERMES_SLOW_ASSERT( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"unaccounted handles were created\"); auto objHandle = runtime->makeHandle(obj); auto cacheHCPtr = vmcast_or_null(static_cast( cacheEntry->clazz.get(runtime, &runtime->getHeap()))); CAPTURE_IP(runtime->recordHiddenClass( curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr)); \/\/ obj may be moved by GC due to recordHiddenClass obj = objHandle.get(); } gcScope.flushToSmallCount(KEEP_HANDLES); #endif auto clazzGCPtr = obj->getClassGCPtr(); #ifndef NDEBUG if (clazzGCPtr.get(runtime)->isDictionary()) ++NumGetByIdDict; #else (void)NumGetByIdDict; #endif \/\/ If we have a cache hit, reuse the cached offset and immediately \/\/ return the property. if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) { ++NumGetByIdCacheHits; CAPTURE_IP_ASSIGN( O1REG(GetById), JSObject::getNamedSlotValue( obj, runtime, cacheEntry->slot)); ip = nextIP; DISPATCH; } auto id = ID(idVal); NamedPropertyDescriptor desc; CAPTURE_IP_ASSIGN( OptValue fastPathResult, JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc)); if (LLVM_LIKELY( fastPathResult.hasValue() && fastPathResult.getValue()) && !desc.flags.accessor) { ++NumGetByIdFastPaths; \/\/ cacheIdx == 0 indicates no caching so don't update the cache in \/\/ those cases. auto *clazz = clazzGCPtr.getNonNull(runtime); if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) && LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) { #ifdef HERMES_SLOW_DEBUG if (cacheEntry->clazz && cacheEntry->clazz != clazzGCPtr.getStorageType()) ++NumGetByIdCacheEvicts; #else (void)NumGetByIdCacheEvicts; #endif \/\/ Cache the class, id and property slot. cacheEntry->clazz = clazzGCPtr.getStorageType(); cacheEntry->slot = desc.slot; } CAPTURE_IP_ASSIGN( O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc)); ip = nextIP; DISPATCH; } \/\/ The cache may also be populated via the prototype of the object. \/\/ This value is only reliable if the fast path was a definite \/\/ not-found. if (fastPathResult.hasValue() && !fastPathResult.getValue() && !obj->isProxyObject()) { CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime)); \/\/ TODO: This isLazy check is because a lazy object is reported as \/\/ having no properties and therefore cannot contain the property. \/\/ This check does not belong here, it should be merged into \/\/ tryGetOwnNamedDescriptorFast(). if (parent && cacheEntry->clazz == parent->getClassGCPtr().getStorageType() && LLVM_LIKELY(!obj->isLazy())) { ++NumGetByIdProtoHits; CAPTURE_IP_ASSIGN( O1REG(GetById), JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot)); ip = nextIP; DISPATCH; } } #ifdef HERMES_SLOW_DEBUG CAPTURE_IP_ASSIGN( JSObject * propObj, JSObject::getNamedDescriptor( Handle::vmcast(&O2REG(GetById)), runtime, id, desc)); if (propObj) { if (desc.flags.accessor) ++NumGetByIdAccessor; else if (propObj != vmcast(O2REG(GetById))) ++NumGetByIdProto; } else { ++NumGetByIdNotFound; } #else (void)NumGetByIdAccessor; (void)NumGetByIdProto; (void)NumGetByIdNotFound; #endif #ifdef HERMES_SLOW_DEBUG auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry->clazz.get(runtime, &runtime->getHeap()) : nullptr; #endif ++NumGetByIdSlow; CAPTURE_IP_ASSIGN( resPH, JSObject::getNamed_RJS( Handle::vmcast(&O2REG(GetById)), runtime, id, !tryProp ? defaultPropOpFlags : defaultPropOpFlags.plusMustExist(), cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry : nullptr)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } #ifdef HERMES_SLOW_DEBUG if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass && cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) { ++NumGetByIdCacheEvicts; } #endif } else { ++NumGetByIdTransient; assert(!tryProp && \"TryGetById can only be used on the global object\"); \/* Slow path. *\/ CAPTURE_IP_ASSIGN( resPH, Interpreter::getByIdTransient_RJS( runtime, Handle<>(&O2REG(GetById)), ID(idVal))); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } } O1REG(GetById) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(TryPutByIdLong) { tryProp = true; idVal = ip->iTryPutByIdLong.op4; nextIP = NEXTINST(TryPutByIdLong); goto putById; } CASE(PutByIdLong) { tryProp = false; idVal = ip->iPutByIdLong.op4; nextIP = NEXTINST(PutByIdLong); goto putById; } CASE(TryPutById) { tryProp = true; idVal = ip->iTryPutById.op4; nextIP = NEXTINST(TryPutById); goto putById; } CASE(PutById) { tryProp = false; idVal = ip->iPutById.op4; nextIP = NEXTINST(PutById); } putById : { ++NumPutById; if (LLVM_LIKELY(O1REG(PutById).isObject())) { auto *obj = vmcast(O1REG(PutById)); auto cacheIdx = ip->iPutById.op3; auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx); #ifdef HERMESVM_PROFILER_BB { HERMES_SLOW_ASSERT( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"unaccounted handles were created\"); auto objHandle = runtime->makeHandle(obj); auto cacheHCPtr = vmcast_or_null(static_cast( cacheEntry->clazz.get(runtime, &runtime->getHeap()))); CAPTURE_IP(runtime->recordHiddenClass( curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr)); \/\/ obj may be moved by GC due to recordHiddenClass obj = objHandle.get(); } gcScope.flushToSmallCount(KEEP_HANDLES); #endif auto clazzGCPtr = obj->getClassGCPtr(); \/\/ If we have a cache hit, reuse the cached offset and immediately \/\/ return the property. if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) { ++NumPutByIdCacheHits; CAPTURE_IP(JSObject::setNamedSlotValue( obj, runtime, cacheEntry->slot, O2REG(PutById))); ip = nextIP; DISPATCH; } auto id = ID(idVal); NamedPropertyDescriptor desc; CAPTURE_IP_ASSIGN( OptValue hasOwnProp, JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc)); if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) && !desc.flags.accessor && desc.flags.writable && !desc.flags.internalSetter) { ++NumPutByIdFastPaths; \/\/ cacheIdx == 0 indicates no caching so don't update the cache in \/\/ those cases. auto *clazz = clazzGCPtr.getNonNull(runtime); if (LLVM_LIKELY(!clazz->isDictionary()) && LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) { #ifdef HERMES_SLOW_DEBUG if (cacheEntry->clazz && cacheEntry->clazz != clazzGCPtr.getStorageType()) ++NumPutByIdCacheEvicts; #else (void)NumPutByIdCacheEvicts; #endif \/\/ Cache the class and property slot. cacheEntry->clazz = clazzGCPtr.getStorageType(); cacheEntry->slot = desc.slot; } CAPTURE_IP(JSObject::setNamedSlotValue( obj, runtime, desc.slot, O2REG(PutById))); ip = nextIP; DISPATCH; } CAPTURE_IP_ASSIGN( auto putRes, JSObject::putNamed_RJS( Handle::vmcast(&O1REG(PutById)), runtime, id, Handle<>(&O2REG(PutById)), !tryProp ? defaultPropOpFlags : defaultPropOpFlags.plusMustExist())); if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) { goto exception; } } else { ++NumPutByIdTransient; assert(!tryProp && \"TryPutById can only be used on the global object\"); CAPTURE_IP_ASSIGN( auto retStatus, Interpreter::putByIdTransient_RJS( runtime, Handle<>(&O1REG(PutById)), ID(idVal), Handle<>(&O2REG(PutById)), strictMode)); if (retStatus == ExecutionStatus::EXCEPTION) { goto exception; } } gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(GetByVal) { CallResult propRes{ExecutionStatus::EXCEPTION}; if (LLVM_LIKELY(O2REG(GetByVal).isObject())) { CAPTURE_IP_ASSIGN( resPH, JSObject::getComputed_RJS( Handle::vmcast(&O2REG(GetByVal)), runtime, Handle<>(&O3REG(GetByVal)))); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } } else { \/\/ This is the \"slow path\". CAPTURE_IP_ASSIGN( resPH, Interpreter::getByValTransient_RJS( runtime, Handle<>(&O2REG(GetByVal)), Handle<>(&O3REG(GetByVal)))); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(GetByVal) = resPH->get(); ip = NEXTINST(GetByVal); DISPATCH; } CASE(PutByVal) { if (LLVM_LIKELY(O1REG(PutByVal).isObject())) { CAPTURE_IP_ASSIGN( auto putRes, JSObject::putComputed_RJS( Handle::vmcast(&O1REG(PutByVal)), runtime, Handle<>(&O2REG(PutByVal)), Handle<>(&O3REG(PutByVal)), defaultPropOpFlags)); if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) { goto exception; } } else { \/\/ This is the \"slow path\". CAPTURE_IP_ASSIGN( auto retStatus, Interpreter::putByValTransient_RJS( runtime, Handle<>(&O1REG(PutByVal)), Handle<>(&O2REG(PutByVal)), Handle<>(&O3REG(PutByVal)), strictMode)); if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) { goto exception; } } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(PutByVal); DISPATCH; } CASE(PutOwnByIndexL) { nextIP = NEXTINST(PutOwnByIndexL); idVal = ip->iPutOwnByIndexL.op3; goto putOwnByIndex; } CASE(PutOwnByIndex) { nextIP = NEXTINST(PutOwnByIndex); idVal = ip->iPutOwnByIndex.op3; } putOwnByIndex : { tmpHandle = HermesValue::encodeDoubleValue(idVal); CAPTURE_IP(JSObject::defineOwnComputedPrimitive( Handle::vmcast(&O1REG(PutOwnByIndex)), runtime, tmpHandle, DefinePropertyFlags::getDefaultNewPropertyFlags(), Handle<>(&O2REG(PutOwnByIndex)))); gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = nextIP; DISPATCH; } CASE(GetPNameList) { CAPTURE_IP_ASSIGN( auto pRes, handleGetPNameList(runtime, frameRegs, ip)); if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(GetPNameList); DISPATCH; } CASE(GetNextPName) { { assert( vmisa(O2REG(GetNextPName)) && \"GetNextPName's second op must be BigStorage\"); auto obj = Handle::vmcast(&O3REG(GetNextPName)); auto arr = Handle::vmcast(&O2REG(GetNextPName)); uint32_t idx = O4REG(GetNextPName).getNumber(); uint32_t size = O5REG(GetNextPName).getNumber(); MutableHandle propObj{runtime}; \/\/ Loop until we find a property which is present. while (idx < size) { tmpHandle = arr->at(idx); ComputedPropertyDescriptor desc; CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor( obj, runtime, tmpHandle, propObj, desc)); if (LLVM_LIKELY(propObj)) break; ++idx; } if (idx < size) { \/\/ We must return the property as a string if (tmpHandle->isNumber()) { CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle)); assert( status == ExecutionStatus::RETURNED && \"toString on number cannot fail\"); tmpHandle = status->getHermesValue(); } O1REG(GetNextPName) = tmpHandle.get(); O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1); } else { O1REG(GetNextPName) = HermesValue::encodeUndefinedValue(); } } gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = NEXTINST(GetNextPName); DISPATCH; } CASE(ToNumber) { if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) { O1REG(ToNumber) = O2REG(ToNumber); ip = NEXTINST(ToNumber); } else { CAPTURE_IP_ASSIGN( res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber)))); if (res == ExecutionStatus::EXCEPTION) goto exception; gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(ToNumber) = res.getValue(); ip = NEXTINST(ToNumber); } DISPATCH; } CASE(ToInt32) { CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) goto exception; gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(ToInt32) = res.getValue(); ip = NEXTINST(ToInt32); DISPATCH; } CASE(AddEmptyString) { if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) { O1REG(AddEmptyString) = O2REG(AddEmptyString); ip = NEXTINST(AddEmptyString); } else { CAPTURE_IP_ASSIGN( res, toPrimitive_RJS( runtime, Handle<>(&O2REG(AddEmptyString)), PreferredType::NONE)); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) goto exception; tmpHandle = res.getValue(); CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle)); if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) goto exception; tmpHandle.clear(); gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(AddEmptyString) = strRes->getHermesValue(); ip = NEXTINST(AddEmptyString); } DISPATCH; } CASE(Jmp) { ip = IPADD(ip->iJmp.op1); DISPATCH; } CASE(JmpLong) { ip = IPADD(ip->iJmpLong.op1); DISPATCH; } CASE(JmpTrue) { if (toBoolean(O2REG(JmpTrue))) ip = IPADD(ip->iJmpTrue.op1); else ip = NEXTINST(JmpTrue); DISPATCH; } CASE(JmpTrueLong) { if (toBoolean(O2REG(JmpTrueLong))) ip = IPADD(ip->iJmpTrueLong.op1); else ip = NEXTINST(JmpTrueLong); DISPATCH; } CASE(JmpFalse) { if (!toBoolean(O2REG(JmpFalse))) ip = IPADD(ip->iJmpFalse.op1); else ip = NEXTINST(JmpFalse); DISPATCH; } CASE(JmpFalseLong) { if (!toBoolean(O2REG(JmpFalseLong))) ip = IPADD(ip->iJmpFalseLong.op1); else ip = NEXTINST(JmpFalseLong); DISPATCH; } CASE(JmpUndefined) { if (O2REG(JmpUndefined).isUndefined()) ip = IPADD(ip->iJmpUndefined.op1); else ip = NEXTINST(JmpUndefined); DISPATCH; } CASE(JmpUndefinedLong) { if (O2REG(JmpUndefinedLong).isUndefined()) ip = IPADD(ip->iJmpUndefinedLong.op1); else ip = NEXTINST(JmpUndefinedLong); DISPATCH; } CASE(Add) { if (LLVM_LIKELY( O2REG(Add).isNumber() && O3REG(Add).isNumber())) { \/* Fast-path. *\/ CASE(AddN) { O1REG(Add) = HermesValue::encodeDoubleValue( O2REG(Add).getNumber() + O3REG(Add).getNumber()); ip = NEXTINST(Add); DISPATCH; } } CAPTURE_IP_ASSIGN( res, addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add)))); if (res == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(Add) = res.getValue(); ip = NEXTINST(Add); DISPATCH; } CASE(BitNot) { if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { \/* Fast-path. *\/ O1REG(BitNot) = HermesValue::encodeDoubleValue( ~hermes::truncateToInt32(O2REG(BitNot).getNumber())); ip = NEXTINST(BitNot); DISPATCH; } CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot)))); if (res == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(BitNot) = HermesValue::encodeDoubleValue( ~static_cast(res->getNumber())); ip = NEXTINST(BitNot); DISPATCH; } CASE(GetArgumentsLength) { \/\/ If the arguments object hasn't been created yet. if (O2REG(GetArgumentsLength).isUndefined()) { O1REG(GetArgumentsLength) = HermesValue::encodeNumberValue(FRAME.getArgCount()); ip = NEXTINST(GetArgumentsLength); DISPATCH; } \/\/ The arguments object has been created, so this is a regular property \/\/ get. assert( O2REG(GetArgumentsLength).isObject() && \"arguments lazy register is not an object\"); CAPTURE_IP_ASSIGN( resPH, JSObject::getNamed_RJS( Handle::vmcast(&O2REG(GetArgumentsLength)), runtime, Predefined::getSymbolID(Predefined::length))); if (resPH == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(GetArgumentsLength) = resPH->get(); ip = NEXTINST(GetArgumentsLength); DISPATCH; } CASE(GetArgumentsPropByVal) { \/\/ If the arguments object hasn't been created yet and we have a \/\/ valid integer index, we use the fast path. if (O3REG(GetArgumentsPropByVal).isUndefined()) { \/\/ If this is an integer index. if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) { \/\/ Is this an existing argument? if (*index < FRAME.getArgCount()) { O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index); ip = NEXTINST(GetArgumentsPropByVal); DISPATCH; } } } \/\/ Slow path. CAPTURE_IP_ASSIGN( auto res, getArgumentsPropByValSlowPath_RJS( runtime, &O3REG(GetArgumentsPropByVal), &O2REG(GetArgumentsPropByVal), FRAME.getCalleeClosureHandleUnsafe(), strictMode)); if (res == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(GetArgumentsPropByVal) = res->getHermesValue(); ip = NEXTINST(GetArgumentsPropByVal); DISPATCH; } CASE(ReifyArguments) { \/\/ If the arguments object was already created, do nothing. if (!O1REG(ReifyArguments).isUndefined()) { assert( O1REG(ReifyArguments).isObject() && \"arguments lazy register is not an object\"); ip = NEXTINST(ReifyArguments); DISPATCH; } CAPTURE_IP_ASSIGN( resArgs, reifyArgumentsSlowPath( runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode)); if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(ReifyArguments) = resArgs->getHermesValue(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(ReifyArguments); DISPATCH; } CASE(NewObject) { \/\/ Create a new object using the built-in constructor. Note that the \/\/ built-in constructor is empty, so we don't actually need to call \/\/ it. CAPTURE_IP_ASSIGN( O1REG(NewObject), JSObject::create(runtime).getHermesValue()); assert( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"Should not create handles.\"); ip = NEXTINST(NewObject); DISPATCH; } CASE(NewObjectWithParent) { CAPTURE_IP_ASSIGN( O1REG(NewObjectWithParent), JSObject::create( runtime, O2REG(NewObjectWithParent).isObject() ? Handle::vmcast(&O2REG(NewObjectWithParent)) : O2REG(NewObjectWithParent).isNull() ? Runtime::makeNullHandle() : Handle::vmcast(&runtime->objectPrototype)) .getHermesValue()); assert( gcScope.getHandleCountDbg() == KEEP_HANDLES && \"Should not create handles.\"); ip = NEXTINST(NewObjectWithParent); DISPATCH; } CASE(NewObjectWithBuffer) { CAPTURE_IP_ASSIGN( resPH, Interpreter::createObjectFromBuffer( runtime, curCodeBlock, ip->iNewObjectWithBuffer.op3, ip->iNewObjectWithBuffer.op4, ip->iNewObjectWithBuffer.op5)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(NewObjectWithBuffer) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(NewObjectWithBuffer); DISPATCH; } CASE(NewObjectWithBufferLong) { CAPTURE_IP_ASSIGN( resPH, Interpreter::createObjectFromBuffer( runtime, curCodeBlock, ip->iNewObjectWithBufferLong.op3, ip->iNewObjectWithBufferLong.op4, ip->iNewObjectWithBufferLong.op5)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(NewObjectWithBufferLong) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(NewObjectWithBufferLong); DISPATCH; } CASE(NewArray) { \/\/ Create a new array using the built-in constructor. Note that the \/\/ built-in constructor is empty, so we don't actually need to call \/\/ it. CAPTURE_IP_ASSIGN( auto createRes, JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2)); if (createRes == ExecutionStatus::EXCEPTION) { goto exception; } O1REG(NewArray) = createRes->getHermesValue(); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(NewArray); DISPATCH; } CASE(NewArrayWithBuffer) { CAPTURE_IP_ASSIGN( resPH, Interpreter::createArrayFromBuffer( runtime, curCodeBlock, ip->iNewArrayWithBuffer.op2, ip->iNewArrayWithBuffer.op3, ip->iNewArrayWithBuffer.op4)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(NewArrayWithBuffer) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = NEXTINST(NewArrayWithBuffer); DISPATCH; } CASE(NewArrayWithBufferLong) { CAPTURE_IP_ASSIGN( resPH, Interpreter::createArrayFromBuffer( runtime, curCodeBlock, ip->iNewArrayWithBufferLong.op2, ip->iNewArrayWithBufferLong.op3, ip->iNewArrayWithBufferLong.op4)); if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(NewArrayWithBufferLong) = resPH->get(); gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = NEXTINST(NewArrayWithBufferLong); DISPATCH; } CASE(CreateThis) { \/\/ Registers: output, prototype, closure. if (LLVM_UNLIKELY(!vmisa(O3REG(CreateThis)))) { CAPTURE_IP(runtime->raiseTypeError(\"constructor is not callable\")); goto exception; } CAPTURE_IP_ASSIGN( auto res, Callable::newObject( Handle::vmcast(&O3REG(CreateThis)), runtime, Handle::vmcast( O2REG(CreateThis).isObject() ? &O2REG(CreateThis) : &runtime->objectPrototype))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(CreateThis) = res->getHermesValue(); ip = NEXTINST(CreateThis); DISPATCH; } CASE(SelectObject) { \/\/ Registers: output, thisObject, constructorReturnValue. O1REG(SelectObject) = O3REG(SelectObject).isObject() ? O3REG(SelectObject) : O2REG(SelectObject); ip = NEXTINST(SelectObject); DISPATCH; } CASE(Eq) CASE(Neq) { CAPTURE_IP_ASSIGN( res, abstractEqualityTest_RJS( runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq)))); if (res == ExecutionStatus::EXCEPTION) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(Eq) = ip->opCode == OpCode::Eq ? res.getValue() : HermesValue::encodeBoolValue(!res->getBool()); ip = NEXTINST(Eq); DISPATCH; } CASE(StrictEq) { O1REG(StrictEq) = HermesValue::encodeBoolValue( strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq))); ip = NEXTINST(StrictEq); DISPATCH; } CASE(StrictNeq) { O1REG(StrictNeq) = HermesValue::encodeBoolValue( !strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq))); ip = NEXTINST(StrictNeq); DISPATCH; } CASE(Not) { O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not))); ip = NEXTINST(Not); DISPATCH; } CASE(Negate) { if (LLVM_LIKELY(O2REG(Negate).isNumber())) { O1REG(Negate) = HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber()); } else { CAPTURE_IP_ASSIGN( res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate)))); if (res == ExecutionStatus::EXCEPTION) goto exception; gcScope.flushToSmallCount(KEEP_HANDLES); O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber()); } ip = NEXTINST(Negate); DISPATCH; } CASE(TypeOf) { CAPTURE_IP_ASSIGN( O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf)))); ip = NEXTINST(TypeOf); DISPATCH; } CASE(Mod) { \/\/ We use fmod here for simplicity. Theoretically fmod behaves slightly \/\/ differently than the ECMAScript Spec. fmod applies round-towards-zero \/\/ for the remainder when it's not representable by a double; while the \/\/ spec requires round-to-nearest. As an example, 5 % 0.7 will give \/\/ 0.10000000000000031 using fmod, but using the rounding style \/\/ described \/\/ by the spec, the output should really be 0.10000000000000053. \/\/ Such difference can be ignored in practice. if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) { \/* Fast-path. *\/ O1REG(Mod) = HermesValue::encodeDoubleValue( std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber())); ip = NEXTINST(Mod); DISPATCH; } CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod)))); if (res == ExecutionStatus::EXCEPTION) goto exception; double left = res->getDouble(); CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod)))); if (res == ExecutionStatus::EXCEPTION) goto exception; O1REG(Mod) = HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble())); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(Mod); DISPATCH; } CASE(InstanceOf) { CAPTURE_IP_ASSIGN( auto result, instanceOfOperator_RJS( runtime, Handle<>(&O2REG(InstanceOf)), Handle<>(&O3REG(InstanceOf)))); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result); gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(InstanceOf); DISPATCH; } CASE(IsIn) { { if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) { CAPTURE_IP(runtime->raiseTypeError( \"right operand of 'in' is not an object\")); goto exception; } CAPTURE_IP_ASSIGN( auto cr, JSObject::hasComputed( Handle::vmcast(&O3REG(IsIn)), runtime, Handle<>(&O2REG(IsIn)))); if (cr == ExecutionStatus::EXCEPTION) { goto exception; } O1REG(IsIn) = HermesValue::encodeBoolValue(*cr); } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(IsIn); DISPATCH; } CASE(PutNewOwnByIdShort) { nextIP = NEXTINST(PutNewOwnByIdShort); idVal = ip->iPutNewOwnByIdShort.op3; goto putOwnById; } CASE(PutNewOwnNEByIdLong) CASE(PutNewOwnByIdLong) { nextIP = NEXTINST(PutNewOwnByIdLong); idVal = ip->iPutNewOwnByIdLong.op3; goto putOwnById; } CASE(PutNewOwnNEById) CASE(PutNewOwnById) { nextIP = NEXTINST(PutNewOwnById); idVal = ip->iPutNewOwnById.op3; } putOwnById : { assert( O1REG(PutNewOwnById).isObject() && \"Object argument of PutNewOwnById must be an object\"); CAPTURE_IP_ASSIGN( auto res, JSObject::defineNewOwnProperty( Handle::vmcast(&O1REG(PutNewOwnById)), runtime, ID(idVal), ip->opCode <= OpCode::PutNewOwnByIdLong ? PropertyFlags::defaultNewNamedPropertyFlags() : PropertyFlags::nonEnumerablePropertyFlags(), Handle<>(&O2REG(PutNewOwnById)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(DelByIdLong) { idVal = ip->iDelByIdLong.op3; nextIP = NEXTINST(DelByIdLong); goto DelById; } CASE(DelById) { idVal = ip->iDelById.op3; nextIP = NEXTINST(DelById); } DelById : { if (LLVM_LIKELY(O2REG(DelById).isObject())) { CAPTURE_IP_ASSIGN( auto status, JSObject::deleteNamed( Handle::vmcast(&O2REG(DelById)), runtime, ID(idVal), defaultPropOpFlags)); if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue()); } else { \/\/ This is the \"slow path\". CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \/\/ If an exception is thrown, likely we are trying to convert \/\/ undefined\/null to an object. Passing over the name of the property \/\/ so that we could emit more meaningful error messages. CAPTURE_IP(amendPropAccessErrorMsgWithPropName( runtime, Handle<>(&O2REG(DelById)), \"delete\", ID(idVal))); goto exception; } tmpHandle = res.getValue(); CAPTURE_IP_ASSIGN( auto status, JSObject::deleteNamed( Handle::vmcast(tmpHandle), runtime, ID(idVal), defaultPropOpFlags)); if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue()); tmpHandle.clear(); } gcScope.flushToSmallCount(KEEP_HANDLES); ip = nextIP; DISPATCH; } CASE(DelByVal) { if (LLVM_LIKELY(O2REG(DelByVal).isObject())) { CAPTURE_IP_ASSIGN( auto status, JSObject::deleteComputed( Handle::vmcast(&O2REG(DelByVal)), runtime, Handle<>(&O3REG(DelByVal)), defaultPropOpFlags)); if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue()); } else { \/\/ This is the \"slow path\". CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal)))); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { goto exception; } tmpHandle = res.getValue(); CAPTURE_IP_ASSIGN( auto status, JSObject::deleteComputed( Handle::vmcast(tmpHandle), runtime, Handle<>(&O3REG(DelByVal)), defaultPropOpFlags)); if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) { goto exception; } O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue()); } gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); ip = NEXTINST(DelByVal); DISPATCH; } CASE(CreateRegExp) { { \/\/ Create the RegExp object. CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime)); \/\/ Initialize the regexp. CAPTURE_IP_ASSIGN( auto pattern, runtime->makeHandle(curCodeBlock->getRuntimeModule() ->getStringPrimFromStringIDMayAllocate( ip->iCreateRegExp.op2))); CAPTURE_IP_ASSIGN( auto flags, runtime->makeHandle(curCodeBlock->getRuntimeModule() ->getStringPrimFromStringIDMayAllocate( ip->iCreateRegExp.op3))); CAPTURE_IP_ASSIGN( auto bytecode, curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID( ip->iCreateRegExp.op4)); CAPTURE_IP_ASSIGN( auto initRes, JSRegExp::initialize(re, runtime, pattern, flags, bytecode)); if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) { goto exception; } \/\/ Done, return the new object. O1REG(CreateRegExp) = re.getHermesValue(); } gcScope.flushToSmallCount(KEEP_HANDLES); ip = NEXTINST(CreateRegExp); DISPATCH; } CASE(SwitchImm) { if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) { double numVal = O1REG(SwitchImm).getNumber(); uint32_t uintVal = (uint32_t)numVal; if (LLVM_LIKELY(numVal == uintVal) && \/\/ Only integers. LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && \/\/ Bounds checking. LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) \/\/ Bounds checking. { \/\/ Calculate the offset into the bytecode where the jump table for \/\/ this SwitchImm starts. const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr( (const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t)); \/\/ Read the offset from the table. const uint32_t *loc = (const uint32_t *)tablestart + uintVal - ip->iSwitchImm.op4; ip = IPADD(*loc); DISPATCH; } } \/\/ Wrong type or out of range, jump to default. ip = IPADD(ip->iSwitchImm.op3); DISPATCH; } LOAD_CONST( LoadConstUInt8, HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2)); LOAD_CONST( LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2)); LOAD_CONST( LoadConstDouble, HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2)); LOAD_CONST_CAPTURE_IP( LoadConstString, HermesValue::encodeStringValue( curCodeBlock->getRuntimeModule() ->getStringPrimFromStringIDMayAllocate( ip->iLoadConstString.op2))); LOAD_CONST_CAPTURE_IP( LoadConstStringLongIndex, HermesValue::encodeStringValue( curCodeBlock->getRuntimeModule() ->getStringPrimFromStringIDMayAllocate( ip->iLoadConstStringLongIndex.op2))); LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue()); LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue()); LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true)); LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false)); LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0)); BINOP(Sub, doSub); BINOP(Mul, doMult); BINOP(Div, doDiv); BITWISEBINOP(BitAnd, &); BITWISEBINOP(BitOr, |); BITWISEBINOP(BitXor, ^); \/\/ For LShift, we need to use toUInt32 first because lshift on negative \/\/ numbers is undefined behavior in theory. SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t); SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t); SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t); CONDOP(Less, <, lessOp_RJS); CONDOP(LessEq, <=, lessEqualOp_RJS); CONDOP(Greater, >, greaterOp_RJS); CONDOP(GreaterEq, >=, greaterEqualOp_RJS); JCOND(Less, <, lessOp_RJS); JCOND(LessEqual, <=, lessEqualOp_RJS); JCOND(Greater, >, greaterOp_RJS); JCOND(GreaterEqual, >=, greaterEqualOp_RJS); JCOND_STRICT_EQ_IMPL( JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual)); JCOND_STRICT_EQ_IMPL( JStrictEqual, Long, IPADD(ip->iJStrictEqualLong.op1), NEXTINST(JStrictEqualLong)); JCOND_STRICT_EQ_IMPL( JStrictNotEqual, , NEXTINST(JStrictNotEqual), IPADD(ip->iJStrictNotEqual.op1)); JCOND_STRICT_EQ_IMPL( JStrictNotEqual, Long, NEXTINST(JStrictNotEqualLong), IPADD(ip->iJStrictNotEqualLong.op1)); JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual)); JCOND_EQ_IMPL( JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong)); JCOND_EQ_IMPL( JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1)); JCOND_EQ_IMPL( JNotEqual, Long, NEXTINST(JNotEqualLong), IPADD(ip->iJNotEqualLong.op1)); CASE_OUTOFLINE(PutOwnByVal); CASE_OUTOFLINE(PutOwnGetterSetterByVal); CASE_OUTOFLINE(DirectEval); CASE_OUTOFLINE(IteratorBegin); CASE_OUTOFLINE(IteratorNext); CASE(IteratorClose) { if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) { \/\/ The iterator must be closed if it's still an object. \/\/ That means it was never an index and is not done iterating (a state \/\/ which is indicated by `undefined`). CAPTURE_IP_ASSIGN( auto res, iteratorClose( runtime, Handle::vmcast(&O1REG(IteratorClose)), Runtime::getEmptyValue())); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { if (ip->iIteratorClose.op2 && !isUncatchableError(runtime->thrownValue_)) { \/\/ Ignore inner exception. runtime->clearThrownValue(); } else { goto exception; } } gcScope.flushToSmallCount(KEEP_HANDLES); } ip = NEXTINST(IteratorClose); DISPATCH; } CASE(_last) { llvm_unreachable(\"Invalid opcode _last\"); } } llvm_unreachable(\"unreachable\"); \/\/ We arrive here if we couldn't allocate the registers for the current frame. stackOverflow: CAPTURE_IP(runtime->raiseStackOverflow( Runtime::StackOverflowKind::JSRegisterStack)); \/\/ We arrive here when we raised an exception in a callee, but we don't want \/\/ the callee to be able to handle it. handleExceptionInParent: \/\/ Restore the caller code block and IP. curCodeBlock = FRAME.getSavedCodeBlock(); ip = FRAME.getSavedIP(); \/\/ Pop to the previous frame where technically the error happened. frameRegs = &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef(); \/\/ If we are coming from native code, return. if (!curCodeBlock) return ExecutionStatus::EXCEPTION; \/\/ Return because of recursive calling structure #ifdef HERMESVM_PROFILER_EXTERN return ExecutionStatus::EXCEPTION; #endif \/\/ Handle the exception. exception: UPDATE_OPCODE_TIME_SPENT; assert( !runtime->thrownValue_.isEmpty() && \"thrownValue unavailable at exception\"); bool catchable = true; \/\/ If this is an Error object that was thrown internally, it didn't have \/\/ access to the current codeblock and IP, so collect the stack trace here. if (auto *jsError = dyn_vmcast(runtime->thrownValue_)) { catchable = jsError->catchable(); if (!jsError->getStackTrace()) { \/\/ Temporarily clear the thrown value for following operations. CAPTURE_IP_ASSIGN( auto errorHandle, runtime->makeHandle(vmcast(runtime->thrownValue_))); runtime->clearThrownValue(); CAPTURE_IP(JSError::recordStackTrace( errorHandle, runtime, false, curCodeBlock, ip)); \/\/ Restore the thrown value. runtime->setThrownValue(errorHandle.getHermesValue()); } } gcScope.flushToSmallCount(KEEP_HANDLES); tmpHandle.clear(); #ifdef HERMES_ENABLE_DEBUGGER if (SingleStep) { \/\/ If we're single stepping, don't bother with any more checks, \/\/ and simply signal that we should continue execution with an exception. state.codeBlock = curCodeBlock; state.offset = CUROFFSET; return ExecutionStatus::EXCEPTION; } using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode; auto mode = runtime->debugger_.getPauseOnThrowMode(); if (mode != PauseOnThrowMode::None) { if (!runtime->debugger_.isDebugging()) { \/\/ Determine whether the PauseOnThrowMode requires us to stop here. bool caught = runtime->debugger_ .findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET)) .hasValue(); bool shouldStop = mode == PauseOnThrowMode::All || (mode == PauseOnThrowMode::Uncaught && !caught); if (shouldStop) { \/\/ When runDebugger is invoked after an exception, \/\/ stepping should never happen internally. \/\/ Any step is a step to an exception handler, which we do \/\/ directly here in the interpreter. \/\/ Thus, the result state should be the same as the input state. InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET}; CAPTURE_IP_ASSIGN( ExecutionStatus resultStatus, runtime->debugger_.runDebugger( Debugger::RunReason::Exception, tmpState)); (void)resultStatus; assert( tmpState == InterpreterState(curCodeBlock, CUROFFSET) && \"not allowed to step internally in a pauseOnThrow\"); gcScope.flushToSmallCount(KEEP_HANDLES); } } } #endif int32_t handlerOffset = 0; \/\/ If the exception is not catchable, skip found catch blocks. while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) == -1) || !catchable) { PROFILER_EXIT_FUNCTION(curCodeBlock); #ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES runtime->popCallStack(); #endif \/\/ Restore the code block and IP. curCodeBlock = FRAME.getSavedCodeBlock(); ip = FRAME.getSavedIP(); \/\/ Pop a stack frame. frameRegs = &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef(); SLOW_DEBUG( dbgs() << \"function exit with exception: restored stackLevel=\" << runtime->getStackLevel() << \"\\n\"); \/\/ Are we returning to native code? if (!curCodeBlock) { SLOW_DEBUG( dbgs() << \"function exit with exception: returning to native code\\n\"); return ExecutionStatus::EXCEPTION; } assert( isCallType(ip->opCode) && \"return address is not Call-type instruction\"); \/\/ Return because of recursive calling structure #ifdef HERMESVM_PROFILER_EXTERN return ExecutionStatus::EXCEPTION; #endif } INIT_STATE_FOR_CODEBLOCK(curCodeBlock); ip = IPADD(handlerOffset - CUROFFSET); } }","output":{"is_vulnerable":"True","vulnerability_types":["Improper Check or Handling of Exceptional Conditions"],"explanation":"An Integer signedness error in the JavaScript Interpreter in Facebook Hermes prior to commit 2c7af7ec481ceffd0d14ce2d7c045e475fd71dc6 allows attackers to cause a denial of service attack or a potential RCE via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.","severity_level":"NoInfo","cwe":"CWE-703","cve":"CVE-2020-1913"}} -{"idx":486445,"input":"template CImg& _draw_object3d(void *const pboard, CImg& zbuffer, const float X, const float Y, const float Z, const CImg& vertices, const CImgList& primitives, const CImgList& colors, const to& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float sprite_scale) { typedef typename cimg::superset2::type tpfloat; typedef typename to::value_type _to; if (is_empty() || !vertices || !primitives) return *this; CImg error_message(1024); if (!vertices.is_object3d(primitives,colors,opacities,false,error_message)) throw CImgArgumentException(_cimg_instance \"draw_object3d(): Invalid specified 3d object (%u,%u) (%s).\", cimg_instance,vertices._width,primitives._width,error_message.data()); #ifndef cimg_use_board if (pboard) return *this; #endif if (render_type==5) cimg::mutex(10); \/\/ Static variable used in this case, breaks thread-safety. const float nspec = 1 - (specular_lightness<0.0f?0.0f:(specular_lightness>1.0f?1.0f:specular_lightness)), nspec2 = 1 + (specular_shininess<0.0f?0.0f:specular_shininess), nsl1 = (nspec2 - 1)\/cimg::sqr(nspec - 1), nsl2 = 1 - 2*nsl1*nspec, nsl3 = nspec2 - nsl1 - nsl2; \/\/ Create light texture for phong-like rendering. CImg light_texture; if (render_type==5) { if (colors._width>primitives._width) { static CImg default_light_texture; static const tc *lptr = 0; static tc ref_values[64] = { 0 }; const CImg& img = colors.back(); bool is_same_texture = (lptr==img._data); if (is_same_texture) for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) if (ref_values[r++]!=img(i*img._width\/9,j*img._height\/9,0,(i + j)%img._spectrum)) { is_same_texture = false; break; } if (!is_same_texture || default_light_texture._spectrum<_spectrum) { (default_light_texture.assign(img,false)\/=255).resize(-100,-100,1,_spectrum); lptr = colors.back().data(); for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) ref_values[r++] = img(i*img._width\/9,j*img._height\/9,0,(i + j)%img._spectrum); } light_texture.assign(default_light_texture,true); } else { static CImg default_light_texture; static float olightx = 0, olighty = 0, olightz = 0, ospecular_shininess = 0; if (!default_light_texture || lightx!=olightx || lighty!=olighty || lightz!=olightz || specular_shininess!=ospecular_shininess || default_light_texture._spectrum<_spectrum) { default_light_texture.assign(512,512); const float dlx = lightx - X, dly = lighty - Y, dlz = lightz - Z, nl = cimg::hypot(dlx,dly,dlz), nlx = (default_light_texture._width - 1)\/2*(1 + dlx\/nl), nly = (default_light_texture._height - 1)\/2*(1 + dly\/nl), white[] = { 1 }; default_light_texture.draw_gaussian(nlx,nly,default_light_texture._width\/3.0f,white); cimg_forXY(default_light_texture,x,y) { const float factor = default_light_texture(x,y); if (factor>nspec) default_light_texture(x,y) = std::min(2.0f,nsl1*factor*factor + nsl2*factor + nsl3); } default_light_texture.resize(-100,-100,1,_spectrum); olightx = lightx; olighty = lighty; olightz = lightz; ospecular_shininess = specular_shininess; } light_texture.assign(default_light_texture,true); } } \/\/ Compute 3d to 2d projection. CImg projections(vertices._width,2); tpfloat parallzmin = cimg::type::max(); const float absfocale = focale?cimg::abs(focale):0; if (absfocale) { cimg_pragma_openmp(parallel for cimg_openmp_if(projections.size()>4096)) cimg_forX(projections,l) { \/\/ Perspective projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); const tpfloat projectedz = z + Z + absfocale; projections(l,1) = Y + absfocale*y\/projectedz; projections(l,0) = X + absfocale*x\/projectedz; } } else { cimg_pragma_openmp(parallel for cimg_openmp_if(projections.size()>4096)) cimg_forX(projections,l) { \/\/ Parallel projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); if (z visibles(primitives._width,1,1,1,~0U); CImg zrange(primitives._width); const tpfloat zmin = absfocale?(tpfloat)(1.5f - absfocale):cimg::type::min(); bool is_forward = zbuffer?true:false; cimg_pragma_openmp(parallel for cimg_openmp_if(primitives.size()>4096)) cimglist_for(primitives,l) { const CImg& primitive = primitives[l]; switch (primitive.size()) { case 1 : { \/\/ Point CImg<_to> _opacity; __draw_object3d(opacities,l,_opacity); if (l<=colors.width() && (colors[l].size()!=_spectrum || _opacity)) is_forward = false; const unsigned int i0 = (unsigned int)primitive(0); const tpfloat z0 = Z + vertices(i0,2); if (z0>zmin) { visibles(l) = (unsigned int)l; zrange(l) = z0; } } break; case 5 : { \/\/ Sphere const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat Xc = 0.5f*((float)vertices(i0,0) + (float)vertices(i1,0)), Yc = 0.5f*((float)vertices(i0,1) + (float)vertices(i1,1)), Zc = 0.5f*((float)vertices(i0,2) + (float)vertices(i1,2)), _zc = Z + Zc, zc = _zc + _focale, xc = X + Xc*(absfocale?absfocale\/zc:1), yc = Y + Yc*(absfocale?absfocale\/zc:1), radius = 0.5f*cimg::hypot(vertices(i1,0) - vertices(i0,0), vertices(i1,1) - vertices(i0,1), vertices(i1,2) - vertices(i0,2))*(absfocale?absfocale\/zc:1), xm = xc - radius, ym = yc - radius, xM = xc + radius, yM = yc + radius; if (xM>=0 && xm<_width && yM>=0 && ym<_height && _zc>zmin) { visibles(l) = (unsigned int)l; zrange(l) = _zc; } is_forward = false; } break; case 2 : \/\/ Segment case 6 : { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2); tpfloat xm, xM, ym, yM; if (x0=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1)\/2; } } break; case 3 : \/\/ Triangle case 9 : { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2); tpfloat xm, xM, ym, yM; if (x0xM) xM = x2; if (y0yM) yM = y2; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin) { const tpfloat d = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0); if (is_double_sided || d<0) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1 + z2)\/3; } } } break; case 4 : \/\/ Rectangle case 12 : { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = (unsigned int)primitive(3); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2), x3 = projections(i3,0), y3 = projections(i3,1), z3 = Z + vertices(i3,2); tpfloat xm, xM, ym, yM; if (x0xM) xM = x2; if (x3xM) xM = x3; if (y0yM) yM = y2; if (y3yM) yM = y3; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin && z3>zmin) { const float d = (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0); if (is_double_sided || d<0) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1 + z2 + z3)\/4; } } } break; default : if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance \"draw_object3d(): Invalid primitive[%u] with size %u \" \"(should have size 1,2,3,4,5,6,9 or 12).\", cimg_instance, l,primitive.size()); } } \/\/ Force transparent primitives to be drawn last when zbuffer is activated \/\/ (and if object contains no spheres or sprites). if (is_forward) cimglist_for(primitives,l) if (___draw_object3d(opacities,l)!=1) zrange(l) = 2*zmax - zrange(l); \/\/ Sort only visibles primitives. unsigned int *p_visibles = visibles._data; tpfloat *p_zrange = zrange._data; const tpfloat *ptrz = p_zrange; cimg_for(visibles,ptr,unsigned int) { if (*ptr!=~0U) { *(p_visibles++) = *ptr; *(p_zrange++) = *ptrz; } ++ptrz; } const unsigned int nb_visibles = (unsigned int)(p_zrange - zrange._data); if (!nb_visibles) { if (render_type==5) cimg::mutex(10,0); return *this; } CImg permutations; CImg(zrange._data,nb_visibles,1,1,1,true).sort(permutations,is_forward); \/\/ Compute light properties CImg lightprops; switch (render_type) { case 3 : { \/\/ Flat Shading lightprops.assign(nb_visibles); cimg_pragma_openmp(parallel for cimg_openmp_if(nb_visibles>4096)) cimg_forX(lightprops,l) { const CImg& primitive = primitives(visibles(permutations(l))); const unsigned int psize = (unsigned int)primitive.size(); if (psize==3 || psize==4 || psize==9 || psize==12) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nx = dy1*dz2 - dz1*dy2, ny = dz1*dx2 - dx1*dz2, nz = dx1*dy2 - dy1*dx2, norm = 1e-5f + cimg::hypot(nx,ny,nz), lx = X + (x0 + x1 + x2)\/3 - lightx, ly = Y + (y0 + y1 + y2)\/3 - lighty, lz = Z + (z0 + z1 + z2)\/3 - lightz, nl = 1e-5f + cimg::hypot(lx,ly,lz), factor = std::max(cimg::abs(-lx*nx - ly*ny - lz*nz)\/(norm*nl),(tpfloat)0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } else lightprops[l] = 1; } } break; case 4 : \/\/ Gouraud Shading case 5 : { \/\/ Phong-Shading CImg vertices_normals(vertices._width,6,1,1,0); cimg_pragma_openmp(parallel for cimg_openmp_if(nb_visibles>4096)) for (unsigned int l = 0; l& primitive = primitives[visibles(l)]; const unsigned int psize = (unsigned int)primitive.size(); const bool triangle_flag = (psize==3) || (psize==9), rectangle_flag = (psize==4) || (psize==12); if (triangle_flag || rectangle_flag) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = rectangle_flag?(unsigned int)primitive(3):0; const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nnx = dy1*dz2 - dz1*dy2, nny = dz1*dx2 - dx1*dz2, nnz = dx1*dy2 - dy1*dx2, norm = 1e-5f + cimg::hypot(nnx,nny,nnz), nx = nnx\/norm, ny = nny\/norm, nz = nnz\/norm; unsigned int ix = 0, iy = 1, iz = 2; if (is_double_sided && nz>0) { ix = 3; iy = 4; iz = 5; } vertices_normals(i0,ix)+=nx; vertices_normals(i0,iy)+=ny; vertices_normals(i0,iz)+=nz; vertices_normals(i1,ix)+=nx; vertices_normals(i1,iy)+=ny; vertices_normals(i1,iz)+=nz; vertices_normals(i2,ix)+=nx; vertices_normals(i2,iy)+=ny; vertices_normals(i2,iz)+=nz; if (rectangle_flag) { vertices_normals(i3,ix)+=nx; vertices_normals(i3,iy)+=ny; vertices_normals(i3,iz)+=nz; } } } if (is_double_sided) cimg_forX(vertices_normals,p) { const float nx0 = vertices_normals(p,0), ny0 = vertices_normals(p,1), nz0 = vertices_normals(p,2), nx1 = vertices_normals(p,3), ny1 = vertices_normals(p,4), nz1 = vertices_normals(p,5), n0 = nx0*nx0 + ny0*ny0 + nz0*nz0, n1 = nx1*nx1 + ny1*ny1 + nz1*nz1; if (n1>n0) { vertices_normals(p,0) = -nx1; vertices_normals(p,1) = -ny1; vertices_normals(p,2) = -nz1; } } if (render_type==4) { lightprops.assign(vertices._width); cimg_pragma_openmp(parallel for cimg_openmp_if(nb_visibles>4096)) cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = 1e-5f + cimg::hypot(nx,ny,nz), lx = X + vertices(l,0) - lightx, ly = Y + vertices(l,1) - lighty, lz = Z + vertices(l,2) - lightz, nl = 1e-5f + cimg::hypot(lx,ly,lz), factor = std::max((-lx*nx - ly*ny - lz*nz)\/(norm*nl),(tpfloat)0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } } else { const unsigned int lw2 = light_texture._width\/2 - 1, lh2 = light_texture._height\/2 - 1; lightprops.assign(vertices._width,2); cimg_pragma_openmp(parallel for cimg_openmp_if(nb_visibles>4096)) cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = 1e-5f + cimg::hypot(nx,ny,nz), nnx = nx\/norm, nny = ny\/norm; lightprops(l,0) = lw2*(1 + nnx); lightprops(l,1) = lh2*(1 + nny); } } } break; } \/\/ Draw visible primitives const CImg default_color(1,_spectrum,1,1,(tc)200); CImg<_to> _opacity; for (unsigned int l = 0; l& primitive = primitives[n_primitive]; const CImg &__color = n_primitive(), _color = (__color && __color.size()!=_spectrum && __color._spectrum<_spectrum)? __color.get_resize(-100,-100,-100,_spectrum,0):CImg(), &color = _color?_color:(__color?__color:default_color); const tc *const pcolor = color._data; const float opacity = __draw_object3d(opacities,n_primitive,_opacity); #ifdef cimg_use_board LibBoard::Board &board = *(LibBoard::Board*)pboard; #endif switch (primitive.size()) { case 1 : { \/\/ Colored point or sprite const unsigned int n0 = (unsigned int)primitive[0]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1); if (_opacity.is_empty()) { \/\/ Scalar opacity. if (color.size()==_spectrum) { \/\/ Colored point. draw_point(x0,y0,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height()-(float)y0); } #endif } else { \/\/ Sprite. const tpfloat z = Z + vertices(n0,2); const float factor = focale<0?1:sprite_scale*(absfocale?absfocale\/(z + absfocale):1); const unsigned int _sw = (unsigned int)(color._width*factor), _sh = (unsigned int)(color._height*factor), sw = _sw?_sw:1, sh = _sh?_sh:1; const int nx0 = x0 - (int)sw\/2, ny0 = y0 - (int)sh\/2; if (sw<=3*_width\/2 && sh<=3*_height\/2 && (nx0 + (int)sw\/2>=0 || nx0 - (int)sw\/2=0 || ny0 - (int)sh\/2 _sprite = (sw!=color._width || sh!=color._height)? color.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg(), &sprite = _sprite?_sprite:color; draw_image(nx0,ny0,sprite,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128); board.setFillColor(LibBoard::Color::Null); board.drawRectangle((float)nx0,height() - (float)ny0,sw,sh); } #endif } } } else { \/\/ Opacity mask. const tpfloat z = Z + vertices(n0,2); const float factor = focale<0?1:sprite_scale*(absfocale?absfocale\/(z + absfocale):1); const unsigned int _sw = (unsigned int)(std::max(color._width,_opacity._width)*factor), _sh = (unsigned int)(std::max(color._height,_opacity._height)*factor), sw = _sw?_sw:1, sh = _sh?_sh:1; const int nx0 = x0 - (int)sw\/2, ny0 = y0 - (int)sh\/2; if (sw<=3*_width\/2 && sh<=3*_height\/2 && (nx0 + (int)sw\/2>=0 || nx0 - (int)sw\/2=0 || ny0 - (int)sh\/2 _sprite = (sw!=color._width || sh!=color._height)? color.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg(), &sprite = _sprite?_sprite:color; const CImg<_to> _nopacity = (sw!=_opacity._width || sh!=_opacity._height)? _opacity.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg<_to>(), &nopacity = _nopacity?_nopacity:_opacity; draw_image(nx0,ny0,sprite,nopacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128); board.setFillColor(LibBoard::Color::Null); board.drawRectangle((float)nx0,height() - (float)ny0,sw,sh); } #endif } } } break; case 2 : { \/\/ Colored line const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,x1,height() - (float)y1); } #endif } else { draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); } #endif } } break; case 5 : { \/\/ Colored sphere const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], is_wireframe = (unsigned int)primitive[2]; const float Xc = 0.5f*((float)vertices(n0,0) + (float)vertices(n1,0)), Yc = 0.5f*((float)vertices(n0,1) + (float)vertices(n1,1)), Zc = 0.5f*((float)vertices(n0,2) + (float)vertices(n1,2)), zc = Z + Zc + _focale, xc = X + Xc*(absfocale?absfocale\/zc:1), yc = Y + Yc*(absfocale?absfocale\/zc:1), radius = 0.5f*cimg::hypot(vertices(n1,0) - vertices(n0,0), vertices(n1,1) - vertices(n0,1), vertices(n1,2) - vertices(n0,2))*(absfocale?absfocale\/zc:1); switch (render_type) { case 0 : draw_point((int)xc,(int)yc,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot(xc,height() - yc); } #endif break; case 1 : draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity,~0U); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.setFillColor(LibBoard::Color::Null); board.drawCircle(xc,height() - yc,radius); } #endif break; default : if (is_wireframe) draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity,~0U); else draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); if (!is_wireframe) board.fillCircle(xc,height() - yc,radius); else { board.setFillColor(LibBoard::Color::Null); board.drawCircle(xc,height() - yc,radius); } } #endif break; } } break; case 6 : { \/\/ Textured line if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance \"draw_object3d(): Undefined texture for line primitive [%u].\", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const int tx0 = (int)primitive[2], ty0 = (int)primitive[3], tx1 = (int)primitive[4], ty1 = (int)primitive[5], x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity); else draw_line(x0,y0,x1,y1,color,tx0,ty0,tx1,ty1,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); } #endif } else { draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); } #endif } } break; case 3 : { \/\/ Colored triangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1), x2 = (int)projections(n2,0), y2 = (int)projections(n2,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity).draw_point(x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity).draw_line(zbuffer,x0,y0,z0,x2,y2,z2,pcolor,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity).draw_line(x0,y0,x2,y2,pcolor,opacity). draw_line(x1,y1,x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x0,height() - (float)y0,(float)x2,height() - (float)y2); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor, lightprops(n0),lightprops(n1),lightprops(n2),opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,lightprops(n0),lightprops(n1),lightprops(n2),opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprops(n0), (float)x1,height() - (float)y1,lightprops(n1), (float)x2,height() - (float)y2,lightprops(n2)); } #endif break; case 5 : { const unsigned int lx0 = (unsigned int)lightprops(n0,0), ly0 = (unsigned int)lightprops(n0,1), lx1 = (unsigned int)lightprops(n1,0), ly1 = (unsigned int)lightprops(n1,1), lx2 = (unsigned int)lightprops(n2,0), ly2 = (unsigned int)lightprops(n2,1); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n0,0))), (int)(light_texture.height()\/2*(1 + lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n1,0))), (int)(light_texture.height()\/2*(1 + lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n2,0))), (int)(light_texture.height()\/2*(1 + lightprops(n2,1)))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); } #endif } break; } } break; case 4 : { \/\/ Colored rectangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1), x2 = (int)projections(n2,0), y2 = (int)projections(n2,1), x3 = (int)projections(n3,0), y3 = (int)projections(n3,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity). draw_point(x2,y2,pcolor,opacity).draw_point(x3,y3,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); board.drawDot((float)x3,height() - (float)y3); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity).draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opacity). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,pcolor,opacity).draw_line(zbuffer,x3,y3,z3,x0,y0,z0,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity).draw_line(x1,y1,x2,y2,pcolor,opacity). draw_line(x2,y2,x3,y3,pcolor,opacity).draw_line(x3,y3,x0,y0,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); board.drawLine((float)x2,height() - (float)y2,(float)x3,height() - (float)y3); board.drawLine((float)x3,height() - (float)y3,(float)x0,height() - (float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity).draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opacity,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity,lightprops(l)). _draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp),(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,lightprop0,lightprop1,lightprop2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,lightprop0,lightprop2,lightprop3,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,lightprop0,lightprop1,lightprop2,opacity). draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,lightprop0,lightprop2,lightprop3,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x1,height() - (float)y1,lightprop1, (float)x2,height() - (float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x2,height() - (float)y2,lightprop2, (float)x3,height() - (float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)lightprops(n0,0), ly0 = (unsigned int)lightprops(n0,1), lx1 = (unsigned int)lightprops(n1,0), ly1 = (unsigned int)lightprops(n1,1), lx2 = (unsigned int)lightprops(n2,0), ly2 = (unsigned int)lightprops(n2,1), lx3 = (unsigned int)lightprops(n3,0), ly3 = (unsigned int)lightprops(n3,1); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()\/2*(1 + lx0)), (int)(light_texture.height()\/2*(1 + ly0))), l1 = light_texture((int)(light_texture.width()\/2*(1 + lx1)), (int)(light_texture.height()\/2*(1 + ly1))), l2 = light_texture((int)(light_texture.width()\/2*(1 + lx2)), (int)(light_texture.height()\/2*(1 + ly2))), l3 = light_texture((int)(light_texture.width()\/2*(1 + lx3)), (int)(light_texture.height()\/2*(1 + ly3))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x2,height() - (float)y2,l2, (float)x3,height() - (float)y3,l3); } #endif } break; } } break; case 9 : { \/\/ Textured triangle if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance \"draw_object3d(): Undefined texture for triangle primitive [%u].\", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2]; const int tx0 = (int)primitive[3], ty0 = (int)primitive[4], tx1 = (int)primitive[5], ty1 = (int)primitive[6], tx2 = (int)primitive[7], ty2 = (int)primitive[8], x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1), x2 = (int)projections(n2,0), y2 = (int)projections(n2,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity). draw_point(x2,y2,color.get_vector_at(tx2<=0?0:tx2>=color.width()?color.width() - 1:tx2, ty2<=0?0:ty2>=color.height()?color.height() - 1:ty2)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(zbuffer,x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opacity). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x0,height() - (float)y0,(float)x2,height() - (float)y2); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprops(n0),lightprops(n1),lightprops(n2),opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprops(n0),lightprops(n1),lightprops(n2),opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprops(n0), (float)x1,height() - (float)y1,lightprops(n1), (float)x2,height() - (float)y2,lightprops(n2)); } #endif break; case 5 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n0,0))), (int)(light_texture.height()\/2*(1 + lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n1,0))), (int)(light_texture.height()\/2*(1 + lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()\/2*(1 + lightprops(n2,0))), (int)(light_texture.height()\/2*(1 + lightprops(n2,1)))); board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); } #endif break; } } break; case 12 : { \/\/ Textured quadrangle if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance \"draw_object3d(): Undefined texture for quadrangle primitive [%u].\", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3]; const int tx0 = (int)primitive[4], ty0 = (int)primitive[5], tx1 = (int)primitive[6], ty1 = (int)primitive[7], tx2 = (int)primitive[8], ty2 = (int)primitive[9], tx3 = (int)primitive[10], ty3 = (int)primitive[11], x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1), x2 = (int)projections(n2,0), y2 = (int)projections(n2,1), x3 = (int)projections(n3,0), y3 = (int)projections(n3,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity). draw_point(x2,y2,color.get_vector_at(tx2<=0?0:tx2>=color.width()?color.width() - 1:tx2, ty2<=0?0:ty2>=color.height()?color.height() - 1:ty2)._data,opacity). draw_point(x3,y3,color.get_vector_at(tx3<=0?0:tx3>=color.width()?color.width() - 1:tx3, ty3<=0?0:ty3>=color.height()?color.height() - 1:ty3)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); board.drawDot((float)x3,height() - (float)y3); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opacity). draw_line(zbuffer,x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity). draw_line(x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opacity). draw_line(x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); board.drawLine((float)x2,height() - (float)y2,(float)x3,height() - (float)y3); board.drawLine((float)x3,height() - (float)y3,(float)x0,height() - (float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprop0,lightprop1,lightprop2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, lightprop0,lightprop2,lightprop3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprop0,lightprop1,lightprop2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, lightprop0,lightprop2,lightprop3,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x1,height() - (float)y1,lightprop1, (float)x2,height() - (float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height() -(float)y0,lightprop0, (float)x2,height() - (float)y2,lightprop2, (float)x3,height() - (float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)lightprops(n0,0), ly0 = (unsigned int)lightprops(n0,1), lx1 = (unsigned int)lightprops(n1,0), ly1 = (unsigned int)lightprops(n1,1), lx2 = (unsigned int)lightprops(n2,0), ly2 = (unsigned int)lightprops(n2,1), lx3 = (unsigned int)lightprops(n3,0), ly3 = (unsigned int)lightprops(n3,1); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()\/2*(1 + lx0)), (int)(light_texture.height()\/2*(1 + ly0))), l1 = light_texture((int)(light_texture.width()\/2*(1 + lx1)), (int)(light_texture.height()\/2*(1 + ly1))), l2 = light_texture((int)(light_texture.width()\/2*(1 + lx2)), (int)(light_texture.height()\/2*(1 + ly2))), l3 = light_texture((int)(light_texture.width()\/2*(1 + lx3)), (int)(light_texture.height()\/2*(1 + ly3))); board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); board.fillGouraudTriangle((float)x0,height() -(float)y0,l0, (float)x2,height() - (float)y2,l2, (float)x3,height() - (float)y3,l3); } #endif } break; } } break; } } if (render_type==5) cimg::mutex(10,0); return *this;","output":{"is_vulnerable":"False","vulnerability_types":"None","explanation":"This function is not vulnerable.","severity_level":"NotVulnerable","cwe":"None","cve":"None"}} -{"idx":196944,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MagickPathExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False during convert or mogrify *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MagickPathExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length_ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if (length < 2) { if (chunk) chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\",\"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (*p && ((p-chunk) < (ssize_t) length)) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters\", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 13) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 15) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 17) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { \/* Interpolate *\/ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))\/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } \/* To do: Rewrite using Get\/Set***PixelChannel() *\/ else { \/* Interpolate *\/ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) \/((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneMNGImage();\"); return(image); }","output":{"is_vulnerable":"True","vulnerability_types":["Out-of-bounds Read"],"explanation":"ImageMagick 7.0.6-1 has an out-of-bounds read vulnerability in ReadOneMNGImage in coders\/png.c.","severity_level":"NoInfo","cwe":"CWE-125","cve":"CVE-2017-12640"}} -{"idx":2659,"input":"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; \/* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC *\/ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; \/* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second *\/ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneMNGImage()\"); image=mng_info->image; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { char magic_number[MaxTextExtent]; \/* Verify MNG signature. *\/ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,\"\\212MNG\\r\\n\\032\\n\",8) != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); \/* Initialize some nonzero members of the MngInfo structure. *\/ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; \/* should be False when converting or mogrifying *\/ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,\"MNG\") == 0) { unsigned char *chunk; \/* Read a new chunk. *\/ type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading MNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); \/* read crc word *\/ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"JNGCompressNotSupported\",\"`%s'\",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DeltaPNGNotSupported\",\"`%s'\",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skip to IEND.\"); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG width: %.20g\",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" MNG height: %.20g\",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second\/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; \/* Skip nominal layer count, frame count, and play time *\/ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; \/* Full MNG *\/ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; \/* LC *\/ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; \/* VLC *\/ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,\"WidthOrHeightExceedsLimit\"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, \"%.20gx%.20g+0+0\",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" repeat=%d, final_delay=%.20g, iterations=%.20g\", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"DEFI chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,\"Nonzero object_id in MNG-LC datastream\", \"`%s'\", image->filename); if (object_id > MNG_MAX_OBJECTS) { \/* Instead of using a warning we should allocate a larger MngInfo structure and continue. *\/ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, \"object id too large\",\"`%s'\",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"DEFI cannot redefine a frozen MNG object\",\"`%s'\", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; \/* Extract object offset info. *\/ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" x_off[%d]: %.20g, y_off[%d]: %.20g\", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } \/* Extract object clipping info. *\/ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { \/* Read global PLTE. *\/ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length\/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length\/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { \/* read global tRNS *\/ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { \/* Read global cHRM *\/ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { \/* Read global sRGB. *\/ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { \/* To do: *\/ \/* Read global iCCP. *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"FRAM chunk found in MNG-VLC datastream\",\"`%s'\", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_mode=%d\",mng_info->framing_mode); if (length > 6) { \/* Note the delay and frame clipping boundaries. *\/ p++; \/* framing mode *\/ while (*p && ((p-chunk) < (ssize_t) length)) p++; \/* frame name *\/ p++; \/* frame name terminator *\/ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; \/* change_sync *\/ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay\/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_delay=%.20g\",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout\/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Framing_timeout=%.20g\",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g\", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); \/* Insert a background layer behind the frame if framing_mode is 4. *\/ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" subframe_width=%.20g, subframe_height=%.20g\",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { \/* Allocate next image structure. *\/ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; \/* Read CLIP. *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { \/* Read DISC or SEEK. *\/ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; \/* read MOVE *\/ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; \/* mark loop active *\/ \/* Record starting point. *\/ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" LOOP level %.20g has %.20g iterations \", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { \/* Found end of zero-iteration loop. *\/ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" ENDL: LOOP level %.20g has %.20g remaining iters \", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, \"ImproperImageHeader\"); } } else { short last_level; \/* Finished loop. *\/ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"CLON is not implemented yet\",\"`%s'\", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"MAGN is not implemented yet for nonzero objects\", \"`%s'\",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, \"Unknown MAGN method in MNG datastream\",\"`%s'\", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS \/* Magnify existing objects in the range magn_first to magn_last *\/ #endif if (magn_first == 0 || magn_last == 0) { \/* Save the magnification factors for object 0 *\/ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"PAST is not implemented yet\",\"`%s'\", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"SHOW is not implemented yet\",\"`%s'\", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"pHYg is not implemented.\",\"`%s'\",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"BASI is not implemented yet\",\"`%s'\", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { \/* Not an IHDR or JHDR chunk *\/ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } \/* Process IHDR *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing %c%c%c%c chunk\",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Skipping invisible object\"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); \/* Insert a transparent background layer behind the entire animation if it is not full screen. *\/ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; \/* Make a background rectangle. *\/ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Inserted transparent background layer, W=%.20g, H=%.20g\", (double) mng_info->mng_width,(double) mng_info->mng_height); } } \/* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. *\/ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g\", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif \/* MNG_INSERT_LAYERS *\/ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; \/* Seek back to the beginning of the IHDR or JHDR chunk's length field. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Seeking back to beginning of %c%c%c%c chunk\",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"exit ReadJNGImage() with error\"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Processing MNG MAGN chunk\"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; \/* Allocate next image structure. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocate magnified image\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { \/* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } \/* magnify the rows into the right side of the large image *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the rows to %.20g\",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { \/* To do: get color as function of indexes[x] *\/ \/* if (image->storage_class == PseudoClass) { } *\/ if (magn_methy <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { \/* Interpolate *\/ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))\/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else \/* if (magn_methy == 3 || magn_methy == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))\/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } \/* x *\/ if (SyncAuthenticPixels(large_image,exception) == 0) break; } \/* i *\/ } \/* y *\/ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Delete original image\"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; \/* magnify the columns *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Magnify the columns to %.20g\",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { \/* replicate previous *\/ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } \/* To do: Rewrite using Get\/Set***PixelComponent() *\/ else { \/* Interpolate *\/ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) \/((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) \/((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) \/((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) \/((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else \/* if (magn_methx == 3 || magn_methx == 5) *\/ { \/* Replicate nearest *\/ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { \/* Interpolate *\/ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)\/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { \/* Rescale pixels to Quantum *\/ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished MAGN processing\"); } } \/* Crop_box is with respect to the upper left corner of the MNG. *\/ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Crop the PNG image\"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; \/* Crop_info is with respect to the upper left corner of the image. *\/ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { \/* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. *\/ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) \/* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. *\/ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { \/* To do: fill low byte properly *\/ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading image datastream.\"); } while (LocaleCompare(image_info->magick,\"MNG\") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Finished reading all image datastreams.\"); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { \/* Insert a background layer if nothing else was found. *\/ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No images found. Inserting a background layer.\"); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { \/* Allocate next image structure. *\/ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Allocation failed, returning NULL.\"); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" No beginning\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted, beginning of list not found\", \"`%s'\",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Corrupt list\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"Linked list is corrupted; next_image is NULL\",\"`%s'\", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" First image null\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"image->next for first image is NULL but shouldn't be.\", \"`%s'\",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" No visible images found.\"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,\"No visible images in file\",\"`%s'\",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay\/mng_info->ticks_per_second; else image->start_loop=MagickTrue; \/* Find final nonzero image delay *\/ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" image->delay=%.20g, final_delay=%.20g\",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Before coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g\",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g\",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Coalesce Images\"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" After coalesce:\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene 0 delay=%.20g dispose=%.20g\",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" scene %.20g delay=%.20g dispose=%.20g\",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage();\"); return(image); }","output":{"is_vulnerable":"True","vulnerability_types":["Out-of-bounds Read"],"explanation":"ImageMagick 7.0.6-1 has an out-of-bounds read vulnerability in ReadOneMNGImage in coders\/png.c.","severity_level":"NoInfo","cwe":"CWE-125","cve":"CVE-2017-12640"}} -{"idx":519226,"input":"void show_edit_form(LOGBOOK *lbs, int message_id, BOOL breply, BOOL bedit, BOOL bupload, BOOL breedit, BOOL bduplicate, BOOL bpreview) { int i, j, n, index, aindex, size, width, height, fh, length, input_size, input_maxlen, format_flags[MAX_N_ATTR], year, month, day, hour, min, sec, n_attr, n_disp_attr, n_lines, attr_index[MAX_N_ATTR], enc_selected, show_text, n_moptions, display_inline, allowed_encoding, thumb_status, max_n_lines, fixed_text, autosave, new_entry, status; char str[2 * NAME_LENGTH], str2[NAME_LENGTH], preset[2 * NAME_LENGTH], *p, *pend, star[80], comment[10000], reply_string[256], list[MAX_N_ATTR][NAME_LENGTH], file_name[256], *buffer, format[256], date[80], script_onload[256], script_onfocus[256], script_onunload[256], attrib[MAX_N_ATTR][NAME_LENGTH], *text, orig_tag[80], reply_tag[MAX_REPLY_TO * 10], att[MAX_ATTACHMENTS][256], encoding[80], slist[MAX_N_ATTR + 10][NAME_LENGTH], svalue[MAX_N_ATTR + 10][NAME_LENGTH], owner[256], locked_by[256], class_value[80], class_name[80], ua[NAME_LENGTH], mid[80], title[256], login_name[256], full_name[256], orig_author[256], attr_moptions[MAX_N_LIST][NAME_LENGTH], ref[256], file_enc[256], tooltip[10000], enc_attr[NAME_LENGTH], user_email[256], cmd[256], thumb_name[256], thumb_ref[256], **user_list, fid[20], upwd[80], subdir[256], draft[256], page_title[300]; time_t now, ltime; char fl[8][NAME_LENGTH]; struct tm *pts; FILE *f; BOOL preset_text, subtable; for (i = 0; i < MAX_ATTACHMENTS; i++) att[i][0] = 0; for (i = 0; i < lbs->n_attr; i++) attrib[i][0] = 0; text = xmalloc(TEXT_SIZE); text[0] = 0; orig_author[0] = 0; orig_tag[0] = 0; encoding[0] = 0; date[0] = 0; locked_by[0] = 0; new_entry = 0; if (!message_id || breply) new_entry = 1; if (isparam(\"new_entry\")) new_entry = 1; \/* check for custom form for new entries *\/ if (!bedit && getcfg(lbs->name, \"Custom new form\", str, sizeof(str))) { \/* check if file starts with an absolute directory *\/ if (str[0] == DIR_SEPARATOR || str[1] == ':') strcpy(file_name, str); else { strlcpy(file_name, logbook_dir, sizeof(file_name)); strlcat(file_name, str, sizeof(file_name)); } send_file_direct(str); return; } \/* check for custom form for editing an entry *\/ if (bedit && getcfg(lbs->name, \"Custom edit form\", str, sizeof(str))) { \/* check if file starts with an absolute directory *\/ if (str[0] == DIR_SEPARATOR || str[1] == ':') strcpy(file_name, str); else { strlcpy(file_name, logbook_dir, sizeof(file_name)); strlcat(file_name, str, sizeof(file_name)); } send_file_direct(str); return; } \/* check for file attachment (mhttpd) *\/ if (isparam(\"fa\")) { strlcpy(att[0], getparam(\"fa\"), 256); \/* remove any leading directory, to accept only files in the logbook directory ! *\/ if (strchr(att[0], DIR_SEPARATOR)) { strlcpy(str, att[0], sizeof(str)); strlcpy(att[0], strrchr(str, DIR_SEPARATOR) + 1, 256); } } if (breedit || bupload) { \/* get date from parameter *\/ if (isparam(\"entry_date\")) strlcpy(date, getparam(\"entry_date\"), sizeof(date)); \/* get attributes from parameters *\/ attrib_from_param(lbs->n_attr, attrib); strlcpy(text, getparam(\"text\"), TEXT_SIZE); for (i = 0; i < MAX_ATTACHMENTS; i++) { sprintf(str, \"attachment%d\", i); if (isparam(str)) strlcpy(att[i], getparam(str), 256); } if (isparam(\"inlineatt\")) { for (i = 0; i < MAX_ATTACHMENTS; i++) { sprintf(str, \"attachment%d\", i); if (!isparam(str) && isparam(\"inlineatt\")) { strlcpy(att[i], getparam(\"inlineatt\"), 256); break; } } } \/* get encoding *\/ strlcpy(encoding, isparam(\"encoding\") ? getparam(\"encoding\") : \"\", sizeof(encoding)); if (!strieq(encoding, \"plain\") && !strieq(encoding, \"ELCode\") && !strieq(encoding, \"HTML\")) strcpy(encoding, \"plain\"); } else { if (message_id) { \/* get message for reply\/edit *\/ size = TEXT_SIZE; el_retrieve(lbs, message_id, date, attr_list, attrib, lbs->n_attr, text, &size, orig_tag, reply_tag, att, encoding, locked_by, draft); get_author(lbs, attrib, orig_author); \/* strip attachments on duplicate *\/ if (bduplicate) memset(att, 0, sizeof(att)); } else if (isparam(\"nsel\")) { \/* multi edit: get all entries and check if attributes are the same *\/ memset(attrib, 0, sizeof(attrib)); for (i = n = 0; i < atoi(getparam(\"nsel\")); i++) { sprintf(str, \"s%d\", i); if (isparam(str)) compare_attributes(lbs, atoi(getparam(str)), attrib, &n); } } } if (message_id && getcfg(lbs->name, \"Use Lock\", str, sizeof(str)) && atoi(str) == 1 && locked_by[0] && !isparam(\"steal\")) { sprintf(str, \"%d\", message_id); sprintf(text, \"%s %s\", loc(\"Entry is currently edited by\"), locked_by); sprintf(cmd, \"?cmd=%s&steal=1\", loc(\"Edit\")); show_query(lbs, loc(\"Entry is locked\"), text, loc(\"Edit anyhow\"), cmd, loc(\"Cancel\"), str); return; } \/* Determine encoding *\/ if (getcfg(lbs->name, \"Allowed encoding\", str, sizeof(str))) allowed_encoding = atoi(str); else allowed_encoding = 7; enc_selected = 2; \/* Default is HTML *\/ if (allowed_encoding == 2) \/* select ELCode if the only one allowed *\/ enc_selected = 0; else if (allowed_encoding == 1) \/* select plain if the only one allowed *\/ enc_selected = 1; else if (allowed_encoding == 3) \/* select ELCode if only plain and ELCode allowed *\/ enc_selected = 0; \/* Overwrite from config file *\/ if (getcfg(lbs->name, \"Default Encoding\", str, sizeof(str))) enc_selected = atoi(str); \/* Overwrite from current entry *\/ if (encoding[0]) { if (encoding[0] == 'E') enc_selected = 0; else if (encoding[0] == 'p') enc_selected = 1; else if (encoding[0] == 'H') enc_selected = 2; } show_text = !getcfg(lbs->name, \"Show text\", str, sizeof(str)) || atoi(str) == 1; \/* check for preset attributes without any condition *\/ set_condition(\"\"); for (index = 0; index < lbs->n_attr; index++) { \/* check for preset string *\/ sprintf(str, \"Preset %s\", attr_list[index]); if ((i = getcfg(lbs->name, str, preset, sizeof(preset))) > 0) { if ((!bedit && !breply && !bduplicate) || \/* don't subst on edit or reply *\/ (breedit && i == 2)) { \/* subst on reedit only if preset is under condition *\/ \/* check for index substitution *\/ if (!bedit && strchr(preset, '#')) { \/* get index *\/ get_auto_index(lbs, index, preset, str, sizeof(str)); strcpy(preset, str); } \/* do not format date for date attributes *\/ i = build_subst_list(lbs, slist, svalue, attrib, (attr_flags[index] & (AF_DATE | AF_DATETIME)) == 0); strsubst_list(preset, sizeof(preset), slist, svalue, i); strcpy(attrib[index], preset); } } sprintf(str, \"Preset on first reply %s\", attr_list[index]); if ((i = getcfg(lbs->name, str, preset, sizeof(preset))) > 0 && breply) { if (orig_tag[0] == 0) { if (!breedit || (breedit && i == 2)) { \/* subst on reedit only if preset is under condition *\/ \/* check for index substitution *\/ if (!bedit && (strchr(preset, '%') || strchr(preset, '#'))) { \/* get index *\/ get_auto_index(lbs, index, preset, str, sizeof(str)); strcpy(preset, str); } \/* do not format date for date attributes *\/ i = build_subst_list(lbs, slist, svalue, attrib, (attr_flags[index] & (AF_DATE | AF_DATETIME)) == 0); strsubst_list(preset, sizeof(preset), slist, svalue, i); strcpy(attrib[index], preset); } } } sprintf(str, \"Preset on reply %s\", attr_list[index]); if ((i = getcfg(lbs->name, str, preset, sizeof(preset))) > 0 && breply) { if (!breedit || (breedit && i == 2)) { \/* subst on reedit only if preset is under condition *\/ \/* check for index substitution *\/ if (!bedit && (strchr(preset, '%') || strchr(preset, '#'))) { \/* get index *\/ get_auto_index(lbs, index, preset, str, sizeof(str)); strcpy(preset, str); } \/* do not format date for date attributes *\/ i = build_subst_list(lbs, slist, svalue, attrib, (attr_flags[index] & (AF_DATE | AF_DATETIME)) == 0); strsubst_list(preset, sizeof(preset), slist, svalue, i); strcpy(attrib[index], preset); } } sprintf(str, \"Preset on edit %s\", attr_list[index]); if ((i = getcfg(lbs->name, str, preset, sizeof(preset))) > 0 && bedit) { if (!breedit || (breedit && i == 2)) { \/* subst on reedit only if preset is under condition *\/ \/* check for index substitution *\/ if (!bedit && (strchr(preset, '%') || strchr(preset, '#'))) { \/* get index *\/ get_auto_index(lbs, index, preset, str, sizeof(str)); strcpy(preset, str); } \/* do not format date for date attributes *\/ i = build_subst_list(lbs, slist, svalue, attrib, (attr_flags[index] & (AF_DATE | AF_DATETIME)) == 0); strsubst_list(preset, sizeof(preset), slist, svalue, i); strcpy(attrib[index], preset); } } sprintf(str, \"Preset on duplicate %s\", attr_list[index]); if ((i = getcfg(lbs->name, str, preset, sizeof(preset))) > 0 && bduplicate) { if (!breedit || (breedit && i == 2)) { \/* subst on reedit only if preset is under condition *\/ \/* check for index substitution *\/ if (!bedit && (strchr(preset, '%') || strchr(preset, '#'))) { \/* get index *\/ get_auto_index(lbs, index, preset, str, sizeof(str)); strcpy(preset, str); } \/* do not format date for date attributes *\/ i = build_subst_list(lbs, slist, svalue, attrib, (attr_flags[index] & (AF_DATE | AF_DATETIME)) == 0); strsubst_list(preset, sizeof(preset), slist, svalue, i); strcpy(attrib[index], preset); } } \/* check for p *\/ sprintf(str, \"p%s\", attr_list[index]); if (isparam(str)) strlcpy(attrib[index], getparam(str), NAME_LENGTH); } \/* evaluate conditional attributes *\/ evaluate_conditions(lbs, attrib); \/* rescan attributes if condition set *\/ if (_condition[0]) { n_attr = scan_attributes(lbs->name); if (breedit || bupload) attrib_from_param(n_attr, attrib); \/* now check again for conditional preset *\/ for (index = 0; index < lbs->n_attr; index++) { \/* check for preset string *\/ sprintf(str, \"Preset %s\", attr_list[index]); if ((i = getcfg(lbs->name, str, preset, sizeof(preset))) > 0) { if ((!bedit && !breply && !bduplicate) || \/* don't subst on edit or reply *\/ (breedit && i == 2)) { \/* subst on reedit only if preset is under condition *\/ \/* check for index substitution *\/ if (!bedit && (strchr(preset, '%') || strchr(preset, '#'))) { \/* get index *\/ get_auto_index(lbs, index, preset, str, sizeof(str)); strcpy(preset, str); } \/* do not format date for date attributes *\/ i = build_subst_list(lbs, slist, svalue, attrib, (attr_flags[index] & (AF_DATE | AF_DATETIME)) == 0); strsubst_list(preset, sizeof(preset), slist, svalue, i); strcpy(attrib[index], preset); } } sprintf(str, \"Preset on reply %s\", attr_list[index]); if ((i = getcfg(lbs->name, str, preset, sizeof(preset))) > 0 && breply) { if (!breedit || (breedit && i == 2)) { \/* subst on reedit only if preset is under condition *\/ \/* check for index substitution *\/ if (!bedit && (strchr(preset, '%') || strchr(preset, '#'))) { \/* get index *\/ get_auto_index(lbs, index, preset, str, sizeof(str)); strcpy(preset, str); } \/* do not format date for date attributes *\/ i = build_subst_list(lbs, slist, svalue, attrib, (attr_flags[index] & (AF_DATE | AF_DATETIME)) == 0); strsubst_list(preset, sizeof(preset), slist, svalue, i); strcpy(attrib[index], preset); } } sprintf(str, \"Preset on duplicate %s\", attr_list[index]); if ((i = getcfg(lbs->name, str, preset, sizeof(preset))) > 0 && bduplicate) { if (!breedit || (breedit && i == 2)) { \/* subst on reedit only if preset is under condition *\/ \/* check for index substitution *\/ if (!bedit && (strchr(preset, '%') || strchr(preset, '#'))) { \/* get index *\/ get_auto_index(lbs, index, preset, str, sizeof(str)); strcpy(preset, str); } \/* do not format date for date attributes *\/ i = build_subst_list(lbs, slist, svalue, attrib, (attr_flags[index] & (AF_DATE | AF_DATETIME)) == 0); strsubst_list(preset, sizeof(preset), slist, svalue, i); strcpy(attrib[index], preset); } } } } else \/\/ if (_condition[0]) n_attr = lbs->n_attr; \/* check for maximum number of replies *\/ if (breply) { i = 0; p = strtok(reply_tag, \",\"); while (p) { i++; p = strtok(NULL, \",\"); } if (i >= MAX_REPLY_TO) { sprintf(str, loc(\"Maximum number of replies (%d) exceeded\"), MAX_REPLY_TO); show_error(str); xfree(text); return; } } \/* check for non-allowed branching *\/ if (breply && getcfg(lbs->name, \"Allow branching\", str, sizeof(str)) && atoi(str) == 0) { if (reply_tag[0]) { show_error(\"Branches are not allowed in this logbook\"); xfree(text); return; } } \/* check for author *\/ if (bedit && getcfg(lbs->name, \"Restrict edit\", str, sizeof(str)) && atoi(str) == 1) { if (!is_author(lbs, attrib, owner)) { strencode2(str2, owner, sizeof(str2)); sprintf(str, loc(\"Only user %s<\/b> can edit this entry\"), str2); show_error(str); xfree(text); return; } } if (bedit) { if (isparam(\"nsel\")) { for (i = n = 0; i < atoi(getparam(\"nsel\")); i++) { sprintf(str, \"s%d\", i); if (isparam(str)) { status = check_edit_time(lbs, atoi(getparam(str))); if (!status) { xfree(text); return; } } } } else if (message_id) { status = check_edit_time(lbs, message_id); if (!status) { xfree(text); return; } } } \/* check for locking *\/ if (message_id && bedit && !breedit && !bupload) { if (getcfg(lbs->name, \"Use Lock\", str, sizeof(str)) && atoi(str) == 1) { if (isparam(\"unm\")) get_full_name(lbs, getparam(\"unm\"), str); else strlcpy(str, loc(\"user\"), sizeof(str)); strcat(str, \" \"); strcat(str, loc(\"on\")); strcat(str, \" \"); strcat(str, rem_host); el_lock_message(lbs, message_id, str, TRUE); } } \/* remove attributes for replies *\/ if (breply) { getcfg(lbs->name, \"Remove on reply\", str, sizeof(str)); n = strbreak(str, list, MAX_N_ATTR, \",\", FALSE); for (i = 0; i < n; i++) for (j = 0; j < n_attr; j++) { if (strieq(attr_list[j], list[i])) attrib[j][0] = 0; } } \/* header *\/ if (getcfg(lbs->name, \"Edit Page Title\", str, sizeof(str))) { i = build_subst_list(lbs, (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, NULL, TRUE); strsubst_list(page_title, sizeof(page_title), (char (*)[NAME_LENGTH]) slist, (char (*)[NAME_LENGTH]) svalue, i); strip_html(page_title); } else sprintf(page_title, \"ELOG %s\", lbs->name); show_html_header(lbs, FALSE, page_title, FALSE, FALSE, NULL, FALSE, 0); \/* java script for checking required attributes and to check for cancelled edits *\/ rsprintf(\"